一般在ASP.NET MVC中,在ActionFilterAttribute的OnActionExecuting方法中,我们会得到如下所示的ModelState和ValueProvider:
context.Controller.ViewData.ModelState and context.Controller.ValueProvider
我们如何在 ASP.NET CORE MVC 的 OnActionExecuting 方法中获取 ModelState 和 ValueProvider 对象?
首先,如果你想获取ModelState,你可以使用:
context.ModelState
如果你想获取ActionFilter中的数据,你可以使用
context.ActionArguments["xxx"]
,这里有一个演示:
型号:
public class MySampleModel
{
[Required]
public string Name { get; set; }
}
行动:
[HttpGet]
public IActionResult TestActionFilterAttribute()
{
return View();
}
[HttpPost]
[MySampleActionFilter]
public IActionResult TestActionFilterAttribute(MySampleModel mySampleModel) {
return Ok();
}
查看:
@model MySampleModel
<form method="post">
<input asp-for="Name" />
<input type="submit" value="submit" />
</form>
MySampleActionFilter属性:
public class MySampleActionFilterAttribute : ActionFilterAttribute
{
public override void OnActionExecuting(ActionExecutingContext context)
{
if (!context.ModelState.IsValid)
{
}
var s = context.ActionArguments["mySampleModel"] as MySampleModel;
}
public override void OnActionExecuted(ActionExecutedContext context)
{
}
}