asp.net core 3.1自定义权限过滤器,支持ajax和页面跳转

    public class AuthorizationFilter : IAuthorizationFilter
    {
        public void OnAuthorization(AuthorizationFilterContext context)
        {
            var actionDescriptor = context.ActionDescriptor as Microsoft.AspNetCore.Mvc.Controllers.ControllerActionDescriptor;
            var controller = actionDescriptor.ControllerName;
            var action = actionDescriptor.ActionName;
            var token = context.HttpContext.Request.Cookies["token"];

            //如果controller为login,无需进行权限校验
            if ("login".Equals(controller, StringComparison.OrdinalIgnoreCase)) return;
            //如果token不为空,且token正确,无需进行权限校验,具体代码自己写
            

            var isAjaxRequest = context.HttpContext.Request.Headers.ContainsKey("x-requested-with");
            if (isAjaxRequest)
            {
                var response = new Response
                {
                    Code = 401,
                    Message = "没有登录或登录超时"
                };

                context.Result = new JsonResult(response);
            }
            else
            {
                context.Result = new RedirectToActionResult("login", "login", null);
            }
        }
    }
            services.AddMvc(config =>
            {
                config.Filters.Add<ExceptionFilter>();
                config.Filters.Add<AuthorizationFilter>();
            });

代码很简单,也可以使用中间件来做。但是貌似使用Filter过滤器比较方便。

posted @ 2021-04-07 10:46  屌丝大叔的笔记  阅读(632)  评论(0编辑  收藏  举报