1 public override async Task OnAuthorizationAsync(AuthorizationFilterContext context) 2 { 3 await base.OnAuthorizationAsync(context); 4 5 var descriptor = context.ActionDescriptor as ControllerActionDescriptor; 6 7 //判斷是否跳過受權過濾器 8 if (descriptor.MethodInfo.GetCustomAttributes<AllowAnonymousAttribute>().Any()) 9 { 10 //return; 11 } 12 13 if (descriptor.MethodInfo.IsDefined(typeof(AllowAnonymousAttribute), true)) 14 { 15 //return; 16 } 17 18 if (!context.HttpContext.User.Identity.IsAuthenticated) 19 { 20 context.Result = Unauthorized(); 21 return; 22 } 23 24 //do something 25 }
代碼如上。async
可是發現仍是有坑,ide
GetCustomAttributes()
這個方法在基本的類庫裏邊根本找不到,翻了翻其餘項目 終於讓我找到了!spa
這個方法在這樣一個擴展包中 System.Reflection.Extensions ,引入以後就能找到那個方法了。code