【问题标题】:ASP.NET MVC ActionFilterAttribute inject value before model bindingASP.NET MVC ActionFilterAttribute 在模型绑定之前注入值
【发布时间】:2011-05-15 02:18:54
【问题描述】:

我想创建一个自定义操作过滤器属性,在模型绑定期间可访问的 HttpContext 项中添加一个值。

我尝试将它添加到 OnActionExecuting 中,但似乎模型绑定是在过滤器之前执行的。

你知道我该怎么做吗?也许模型绑定器中有一个我可以覆盖的方法,它将在过滤器之后触发并使用我的过滤器注入的值。

我要做的是注入一个验证上下文(我用来验证的库支持上下文,它是nvalid.net (www.nvalid.net)

我希望能够放置一个属性,例如

[ValidationContext("Prevalidation")]

关于我的 actionresult 方法,以便在我的自定义模型绑定器中发生的验证可以知道在执行验证时要使用哪个上下文。

这就是为什么我不能简单地制作自定义模型绑定器。

【问题讨论】:

    标签: c# .net asp.net asp.net-mvc asp.net-mvc-3


    【解决方案1】:

    我的回答太晚了,但你可以使用

    AuthorizationFilterAttribute
    

    ModelBinders之前执行。

    【讨论】:

      【解决方案2】:

      我已经找到了实现它的方法。

      public class ModelBinder : DefaultModelBinder
      {
          protected override void OnModelUpdated(ControllerContext controllerContext, ModelBindingContext bindingContext)
          {
              var actionName = controllerContext.RouteData.Values["action"] != null
                                       ? controllerContext.RouteData.Values["action"].ToString()
                                       : string.Empty;
      
              var attribute = controllerContext.Controller.GetType().GetMethods()
                  .Where(x => x.Name == actionName)
                  .Where(x => x.GetCustomAttributes(false).Any(a => a.GetType() == typeof(CustomActionFilterAttribute)))
                  .Select(x => x.GetCustomAttributes(typeof(CustomActionFilterAttribute), false).FirstOrDefault())
                  .FirstOrDefault() as CustomActionFilterAttribute;
      
              if(attribute != null && attribute.AnyProperty)
              {
                  // Do what you want
              }
          }
      }
      

      通过反射我可以找到属性并在我的模型绑定器中使用它

      【讨论】:

        【解决方案3】:

        为什么不简单地编写一个自定义模型绑定器并在BindModel 方法中工作?

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2012-06-24
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多