- Asp.net Core五类过滤器:Authorization Filter、Resource Filter、Acton Filter、Exception Filter、Result Filter。优先级逐次递减。
- 过滤器使用
-
public class GlobalFiler: Attribute,IAuthorizationFilter { public void OnAuthorization(AuthorizationFilterContext context) {
context.Result = new JsonResult("全局权限设置"); } } public class MyFilter : Attribute,IActionFilter,IOrderedFilter { public int Order { get; set; } public void OnActionExecuted(ActionExecutedContext context) { } public void OnActionExecuting(ActionExecutingContext context) { } }
//ActionFilterAttribute继承了Attribute、IActionFilter、IOrderedFilter等 public class MyFilter2 : ActionFilterAttribute {
public override void OnActionExecuting(ActionExecutingContext context) {
//如果失败,页面提示
context.Result = new JsonResult("MyFilter2设置,无权限访问"); } }
-
- 过滤器注册,分为两种:全局注册和用Attribute区域注册,用在特定Action上。
- 全局注册Startup.cs
public void ConfigureServices(IServiceCollection services) { services.AddMvc(config => config.Filters.Add(new GlobalFiler())); //services.AddMvc(config => config.Filters.Add(typeof(GlobalFiler))); }
- 区域注册
[Route("api/[controller]")] [MyFilter(Order = 1)] public class ValuesController : Controller { // GET api/values [HttpGet] [MyFilter2(Order = 0)] public IEnumerable<string> Get() { return new string[] { "value1", "value2" }; } }
- 全局注册Startup.cs
- 过滤器执行顺序
- 默认执行顺序:全局过滤器优先于控制器过滤器,控制器过滤器优先于Action方法过滤器。
- 通过IOrderedFilter覆盖默认执行顺序,此接口公开Order属性表示优先级,Order值越小优先级越高。
参考文档:https://www.cnblogs.com/tdfblog/p/filters-in-aspnet-core-mvc.html