ASP.NET MVC ActionFilterAttribute在模型绑定之前注入值

Cha*_*let 6 .net c# asp.net asp.net-mvc asp.net-mvc-3

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

我试图在OnActionExecuting中添加它,但似乎模型绑定在过滤器之前被激活.

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

我想做的是注入验证上下文(我用于验证的库支持上下文,它是nvalid.net(www.nvalid.net)

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

[ValidationContext("Prevalidation")]
Run Code Online (Sandbox Code Playgroud)

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

这就是我不能简单地制作自定义模型装订器的原因.

Cha*_*let 5

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

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
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

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


Dar*_*rov 3

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