How to apply a global filter for all actions where the controler inherits baseController
and is a post?
Already working with Ninject.Web.MVC aka Ninject.Web.Mvc.FilterBindingSyntax
But I do not know how to apply conditional BindFilter
only to post.
kernel.BindFilter<ValidateJsonAntiForgeryTokenAttribute>(System.Web.Mvc.FilterScope.Action, 0).WhenControllerType<baseController>();
...??
This attempt did not work, because I could not add two conditions to BindFilter
I wanted to do something similar to this. One way to do it is to implement your multiple conditions inside of When()
. The WhenControllerType()
method is just a helper that calls When()
and checks the controller type, so you can re-implement that in your own method and add in whatever other logic you need.
Here is how Ninject implements WhenControllerType()
:
public IFilterBindingInNamedWithOrOnSyntax<T> WhenControllerType(Type controllerType)
{
this.When((Func<ControllerContext, ActionDescriptor, bool>) ((controllerContext, actionDescriptor) => (actionDescriptor.ControllerDescriptor.ControllerType == controllerType)));
return this;
}
From that, we know how to get the controller type for our constraint.
To get a binding like you want, we could do something like this (untested):
kernel
.BindFilter<ValidateJsonAntiForgeryTokenAttribute>(System.Web.Mvc.FilterScope.Action, 0)
.When((controllerContext, actionDescriptor) =>
controllerContext.HttpContext.Request.RequestType.ToLower() == "post" &&
typeof(baseController).IsAssignableFrom(actionDescriptor.ControllerDescriptor.ControllerType));