- 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
