Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using IOverrideFilter to override custom ActionFilters

Tags:

asp.net-mvc

I want to use IOverrideFilter interface to override my custom global filter but it is simply not working! Code looks like to be as follow:

public sealed class MyGlobalFilterExceptionAttribute : FilterAttribute, IOverrideFilter
{
    public Type FiltersToOverride
    {
        get { return typeof(ITest); }
    }
}

My global filter has implemented ITest interface. I know I can implement the task in my original global filter but I would like to do so by IOverrideFilter.

Any Idea??

like image 599
Mori Avatar asked Jun 08 '15 15:06

Mori


People also ask

Can we override filters in MVC?

ASP.NET MVC 5 has arrived with a very important feature called Filter Overrides. Using the Filter Overrides feature, we can exclude a specific action method or controller from the global filter or controller level filter. ASP.NET MVC 5 has arrived with a very important feature called Filter Overrides.

Which is the controller method to override authorization filters?

In MVC applications, we can override the filters which are applied at the Global or the Controller level. For example, we have the "Authorize" filter applied at the Controller, which restricts the user types who can access the Controller Methods. This filter will apply on all the methods of the Controller.

Can we override the execution order of these filters in MVC?

ASP.NET MVC 5 has a new feature called Filter Overrides, which allows you to clear or replace certain filter types created in higher scopes. For example, if you created a global action filter or controller action filter, you could override those filters on a case-by-case basis at the controller action level.


1 Answers

The msdn info is not entirely clear about it but IOverrideFilter.FiltersToOverride must be exactly one of the following:

  • IActionFilter
  • IAuthorizationFilter
  • IAuthenticationFilter
  • IExceptionFilter

Basically, you cannot override specific filters, you can only override all the filters of one of the categories above. Have a look a the ProcessOverrideFilters method in the source code.

So, let's say that your ITest filter is of type IActionFilter, then your override will be (The same logic would apply for any other filter category):

public Type FiltersToOverride
{
    get { return typeof(IActionFilter); }
}

You could also use the predefined OverrideActionFilters (and similar predefined override attributes for other filter categories).

For a more fine-grained override, you might need to develop specific solutions like this one or write your own filter provider as in this very nice article

like image 109
Daniel J.G. Avatar answered Nov 15 '22 06:11

Daniel J.G.