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#?

WBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWB
Release: 2023-09-04 13:49:02
forward
1424 people have browsed it

在 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";
      }
   }
}
Copy after login

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";
      }
   }
}
Copy after login

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());
   }
}
Copy after login

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 of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template