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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With