What are the levels at which filters can be applied in ASP .Net MVC C#?
-
29-09-2020 - |
Question
What are the levels at which filters can be applied in ASP .Net MVC C#?
In an ASP .Net MVC application filters can be applied in three levels.
- Action Method Level
- Controller Level
- Global Level
Action Method Level
Filters that are applied at the Action Method level will work only particularly for that action method.
using System.Web.Mvc; namespace DemoMvcApplication.Controllers{ public class HomeController : Controller{ [Authorize] //Action Method Level public string Index(){ return "Index Invoked"; } } }
Controller Level
Controller level filters are applied to all the action methods. The following filter are applicable to all the action methods of the HomeController, but not on other controllers.
using System.Web.Mvc; namespace DemoMvcApplication.Controllers{ [Authorize] //Controller Level public class HomeController : Controller{ public string Index1(){ return "Index1 Invoked"; } public string Index2(){ return "Index2 Invoked"; } } }
Global Level
Global level filters are provided in the Application_Start event of the global.asax.cs file by using default FilterConfig.RegisterGlobalFilters() method. The global filters will be applied to all the controller and action methods of an application.
public class MvcApplication : System.Web.HttpApplication{ protected void Application_Start(){ AreaRegistration.RegisterAllAreas(); FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters); RouteConfig.RegisterRoutes(RouteTable.Routes); BundleConfig.RegisterBundles(BundleTable.Bundles); } } public class FilterConfig{ public static void RegisterGlobalFilters(GlobalFilterCollection filters){ filters.Add(new HandleErrorAttribute()); filters.Add(new AuthorizeAttribute()); } }
Advertisements
Not affiliated with Tutorialspoint