Home >Backend Development >C#.Net Tutorial >At what level can filters be applied in ASP .Net MVC C#?
In an ASP .Net MVC application, filters can be applied at three levels.
In operation method Filters applied by level only apply to that level 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 filters apply to all action methods. The following filters are Applies to all action methods of HomeController but not others controller.
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 filters are provided in the Application_Start event of global.asax.cs Create the file using the default FilterConfig.RegisterGlobalFilters() method. global filter Will be applied to all controllers and action methods of the 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()); } }
The above is the detailed content of At what level can filters be applied in ASP .Net MVC C#?. For more information, please follow other related articles on the PHP Chinese website!