Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Overriding a global action filter

A handful of pages on my website need to use SSL, so I've added [RequireHttps] to the relevant controllers. However, I still want the majority of my pages to always use non-SSL so I successfully used code I found on SO to create a custom [DoNotUseHttps] filter.

To make things easier I'd like to include this non-SSL filter by default, so I added it to the global filters which are set in the Global.asax file. However, I seem to have now created an infinite loop with each filter redirecting to the other.

Which leads me to my question... is there anything I can add to my global filter to detect if the [RequireHttps] has been already applied to the controller?

like image 748
Jonathan Avatar asked Jul 04 '11 19:07

Jonathan


People also ask

What would you use if you wanted to override action filters?

For this, we can use the OverrideActionFilters attribute, on the methods for which we do not need the action filter to be executed. Simply apply this attribute on the controller method and the filter will not be executed for that method.

Can we override 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.

Can we override action method in MVC?

For MVC action command overrides, extend the BaseMVCActionCommand class, and the only method you'll need to override is doProcessAction , which must return void . It's straightforward to override MVC action commands while keeping your code decoupled from the original action methods.


1 Answers

Sure, you can interrogate anything you like about the actions and controllers. To check for RequireHttpsAttribute:

public override void OnActionExecuted(ActionExecutedContext filterContext)
{
    base.OnActionExecuted(filterContext);

    bool requireHttps = filterContext.ActionDescriptor.ControllerDescriptor
        .GetCustomAttributes(typeof(RequireHttpsAttribute), true).Length > 0
 }
like image 86
Kirk Woll Avatar answered Sep 24 '22 01:09

Kirk Woll