Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 757
Charles Ouellet Avatar asked Nov 24 '10 12:11

Charles Ouellet


1 Answers

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

like image 159
Charles Ouellet Avatar answered Sep 28 '22 05:09

Charles Ouellet