Override a Global Filter in MVC for One Method
asp.net-mvc-4, c#
Solution
You can alter your filter to allow multiple by setting `AllowMultiple = true` in the `AttributeUsage` attribute on your attribute class, and add a check so that if the filter is present multiple times, the globally-applied one doesn't execute. The `ActionExecutingContext` that gets passed into `OnActionExecuting()` lets you get the filters applied via `filterContext.ActionDescriptor.GetCustomAttributes()`, so you can use that here.
Then, alter the constructor so that you can pass in a parameter (probably an enum) that it can use to decide which authorisation method to use - the normal one, or this other one. Give that parameter a default value that makes it select the normal auth method. Then, on that one method that needs a different auth method, you can apply the filter with the other value of the parameter. So it might look like this:
public class CustomAuthAttribute : AuthorizeAttribute
{
public CustomAuthAttribute(AuthMethod method = AuthMethod.StandardAuth)
{
//stuff
}
}
[CustomAuth(AuthMethod.WeirdAuth)]
public ActionResult MethodThatNeedsDifferentAuth()
{
//stuff
}
Problem
In my filterConfig, I have registered a global attribute filter, which requires authorization on each of my methods. However, I have one particular method where I want to apply a different authorization filter attribute. How does one accomplish this, if at all possible? Note: I do not want to use the [AllowAnonymous] attribute (which works seamlessly and completely ignores my filter), since I want the request to be authorized, just through a different set of authorization logic on the method.