Home >Backend Development >C#.Net Tutorial >At what level can filters be applied in ASP .Net MVC C#?

At what level can filters be applied in ASP .Net MVC C#?

WBOY
WBOYforward
2023-09-04 13:49:021361browse

在 ASP .Net MVC C# 中可以应用过滤器的级别是什么?

In an ASP .Net MVC application, filters can be applied at three levels.

  • Operation method level
  • Controller level
  • Global level

Operation method level

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

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

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!

Statement:
This article is reproduced at:tutorialspoint.com. If there is any infringement, please contact admin@php.cn delete