.net core自定义授权认证 含3.0及以上版本AllowAnonymous失效解决办法

新建一个类RequestAuthorizeAttribute 继承IAuthorizationFilter

public class RequestAuthorizeAttribute : IAuthorizationFilter{
   public void OnAuthorization(AuthorizationFilterContext context){
      var descriptor = (Microsoft.AspNetCore.Mvc.Controllers.ControllerActionDescriptor)context.ActionDescriptor;
       //若控制器设置[AllowAnonymous] 则为true
       //若控制器没有设置[AllowAnonymous] 则为false
       var allowanyone = descriptor.ControllerTypeInfo.GetCustomAttributes(typeof(IAllowAnonymous), true).Any()
            || descriptor.MethodInfo.GetCustomAttributes(typeof(IAllowAnonymous), true).Any();
   }
}

Startup类 ConfigureServices方法注册

public void ConfigureServices(IServiceCollection services)
        {
            services.AddMvc(option =>
            {
                option.Filters.Add<RequestAuthorizeAttribute>();
            });

            services.AddControllersWithViews();
        }
posted @ 2021-10-18 15:37  kele-cc  阅读(18)  评论(0)    收藏  举报