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.
- [Authorize]
- public class HomeController : Controller
- {
- public ActionResult Index()
- {
- return View();
- }
-
- public ActionResult About()
- {
- ViewBag.Message = "Your application description page.";
-
- return View();
- }
-
- public ActionResult Contact()
- {
- ViewBag.Message = "Your contact page.";
-
- return View();
- }
- }
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.
- [Authorize]
- public class HomeController : Controller
- {
- public ActionResult Index()
- {
- return View();
- }
-
- public ActionResult About()
- {
- ViewBag.Message = "Your application description page.";
- return View();
- }
-
- [OverrideAuthorization]
- public ActionResult Contact()
- {
- ViewBag.Message = "Your contact page.";
- return View();
- }
- }
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...!!!