有没有办法将控制器的ModelState传递(或访问)到ActionFilterAttribute?

Sai*_*udo 4 c# asp.net-mvc attributes

我有一个从动作过滤器属性派生的自定义验证属性.目前,该属性只是设置一个ActionParameter值,指示验证的项目是否良好,然后该操作必须具有逻辑以确定如何处理信息.

 public class SpecialValidatorAttribute: ActionFilterAttribute
 {
     public override void OnActionExecuting(ActionExecutingContext filterContext)
     {
          // ... valdiation work done here ...
          filterContext.ActionParameters["SpecialIsValid"] = resultOfWork;

          base.OnActionExecuting(filterContext);
     }
 }

 [SpecialValidator]
 public ActionResult Index(FormCollection collection, bool SpecialIsValid)
 {
     if(!SpecialIsValid)
         // add a modelstate error here ...

     // ... more stuff
 }
Run Code Online (Sandbox Code Playgroud)

我想在属性的OnActionExecuting()方法中执行ModelState.AddModelError(),这将节省我让控制器执行此逻辑.

我已经尝试将ModelState属性添加到属性,但此数据似乎不可用于传递到属性.

有没有办法从属性中获取对ModelState的访问权限?

Dar*_*rov 8

假设您的控制器类派生自System.Web.Mvc.Controller(可能是这种情况),您可以尝试这样做:

((Controller)filterContext.Controller).ModelState.AddModelError("key", "value");
Run Code Online (Sandbox Code Playgroud)