Override Fiters
Asp.net MVC 5 provides a way to control which filter applies to which controller or action methods. This can be achieved using Override Filters.
As you might be aware that Filters can be applied to controllers or Actions or Global level. We can apply filters at higher levels usually globally or at controller level and then depending on use we can override them at a lower level i.e. Controller and Action respectively.
Let’s apply Authorize attribute which is an Authorization Filter at Global Level.
public static void RegisterGlobalFilters(GlobalFilterCollection filters)
{
filters.Add(new AuthorizeAttribute(){Roles = "Member"});
}
Applying a filter globally will mean that we don’t need to apply it on controller or actions; this is applied by default to all. We can now override the filter at Controller Level as below:
[OverrideAuthorization]
public class TestController : Controller
{
// GET: Test
public ActionResult Index()
{
return View();
}
}
Thus all actions in TestController can now be accessed by all Roles not just users with role Member.
MVC 5 introduces 5 types of override filters:
- [OverrideActionFilters]
- [OverrideAuthentication]
- [OverrideAuthorization]
- [OverrideExceptionFilters]
- [OverrideResultFilters]
These all filters override IOverrideFilter, you can also create your own custom override filters by implementing IOverrideFilter interface.
public class CustomAuthorizationAttribute : FilterAttribute,IOverrideFilter
{
public Type FiltersToOverride
{
get
{
return typeof(IAuthorizationFilter);
}
}
}