Override Authorization Filter In MVC

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. See the code below.
  1.     [Authorize]  
  2.     public class HomeController : Controller  
  3.     {  
  4.         public ActionResult Index()  
  5.         {  
  6.             return View();  
  7.         }  
  8.   
  9.         public ActionResult About()  
  10.         {  
  11.             ViewBag.Message = "Your application description page.";  
  12.   
  13.             return View();  
  14.         }  
  15.   
  16.         public ActionResult Contact()  
  17.         {  
  18.             ViewBag.Message = "Your contact page.";  
  19.   
  20.             return View();  
  21.         }  
  22.     }  
Run the application and you will be redirected to the login page. Even if you click any link, like About or Contact, it will ask you to first log into the application.


Now, our requirement is to restrict the user to access all the pages, except the "Contact" page. To handle this scenario, we have the option to apply the attribute named OverrideAuthorization on the Contact method in the Home controller. Apply this on the method, as below.
  1. [Authorize]  
  2. public class HomeController : Controller  
  3. {  
  4.     public ActionResult Index()  
  5.     {  
  6.         return View();  
  7.     }  
  8.   
  9.     public ActionResult About()  
  10.     {  
  11.         ViewBag.Message = "Your application description page.";  
  12.         return View();  
  13.     }  
  14.   
  15.     [OverrideAuthorization]  
  16.     public ActionResult Contact()  
  17.     {  
  18.         ViewBag.Message = "Your contact page.";  
  19.         return View();  
  20.     }  
  21. }  
That's it. We are done. Run the application and click on the Contact link. You can now access the Contact page.
 
Hope you enjoyed reading it. Happy coding...!!!