asp.net-core - 如何从 ASP.NET CORE ActionFilter 中的 ActionExecutingContext 对象访问 ModelState 和 ValueProvider 对象
问题描述
通常在 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>
MySampleActionFilterAttribute:
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)
{
}
}