Saturday, 7 July 2018

Filter Overrides in ASP.Net MVC 5

Filters
 Five types of filters available with MVC:
  • Authentication filters
  • Authorization filters
  • Action filters
  • Result filters
  • Exception filters
So we have five type filter overrides corresponding to this:
  • OverrideAuthenticationAttribute
  • OverrideAuthorizationAttribute
  • OverrideActionFiltersAttribute
  • OverrideResultAttribute
  • OverrideExceptionAttribute
We can mark any action method with an override filter attribute that essentially clears all filters in an upper scope (in other words controller level or global level).

Example
In the following example, the Authorize Filter is applied at the controller level. So, all the action methods of the Home controller can be accessed by the Admin user only. Now I want to exclude or bypass the Authorize Filter from the "About" method.
[Authorize(Users="Admin")]
public class HomeController : Controller{
    public ActionResult Index()
    {
        ViewBag.Message = "Welcome to ASP.NET MVC!";
        return View();
    } 
    public ActionResult About()
    {
        return View();
    }
}
So in this case we can mark this "About" method with the “OverrideAuthorization” attribute. Now all the action methods of the home controller can be accessed by the Admin user except the "About" method. We can access the "About" action method without any authorization.
[Authorize(Users="Admin")]
public class HomeController : Controller{
    public ActionResult Index()
    {
        ViewBag.Message = "Welcome to ASP.NET MVC!";
        return View();
    }
    [OverrideAuthorization]   

 public ActionResult About()
    {
        return View();
    }
}
Note: The OverrideAuthorizationAttribute does not work properly with MVC version 5.0 due to some internal bug. This bug was resolved in MVC version 5.1.

No comments:

Post a Comment