简体   繁体   中英

ASP.NET MVC ActionFilterAttribute inject value before model binding

I would like to create a custom action filter attribute that adds a value in the HttpContext items that would be accessible during model binding.

I have tried to add it in the OnActionExecuting but it that seems the modelbinding is exectued before the filter.

Do you have any idea how I could do it? Maybe there's a method in the modelbinder that I could override that will be fired after the filter and use the value injected by my filter.

What I want to do, is to inject a validation context (the library I use for validation supports context, it is nvalid.net (www.nvalid.net)

I would like to be able to place an attribute such as

[ValidationContext("Prevalidation")]

on my actionresult method, so that the validation that occurs in my custom model binder could know which context to use when doing the Validation.

That's why I can't simply make a custom model binder.

I have found a way to achieve it.

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
        }
    }
}

By reflection I can find the attribute and use it in my modelbinder

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

I am too late with my answer but you can use

AuthorizationFilterAttribute

It is executed before ModelBinders .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM