ASP.NET MVC实战之权限拦截Authorize使用

发布时间:2023年12月17日

1,具体的实现方法代码如下

 public class CustomAuthorizeAttribute : FilterAttribute, IAuthorizationFilter
    {
        /// <summary>
        /// 如果需要验证权限的时候,就执行进来
        /// </summary>
        /// <param name="filterContext"></param>
        public void OnAuthorization(AuthorizationContext filterContext)
        {
            //1.验证是否登录过
            object ouser = filterContext.HttpContext.Session[CacheConstant.CacheCurrentUser()];
            if (ouser == null || (ouser is CurrentUser) == false) //取到session或者取到的session不是CurrentUser---没有登录
            {
                ResponseResult(filterContext);
            }
            else
            {
                //就要取出当前用户的信息,通过用户信息判断,当前这个用户是否能够访问当前要访问的功能  
                CurrentUser currentUser = (CurrentUser)ouser;

                List<Tuple<string, string, string>> tupMen = currentUser.TupMenue;

                List<string> currentUserUrlList = tupMen.Select(c => c.Item3).Where(c => !string.IsNullOrWhiteSpace(c)).Select(c => c.ToUpper()).ToList();

                object ObjectControllerName = filterContext.HttpContext.Request.RequestContext.RouteData.Values["controller"];
                string controllerName = ObjectControllerName.ToString().ToUpper();
                int count = currentUserUrlList.Count(c => c.Contains(controllerName));
                if (count <= 0)
                {
                    if (filterContext.HttpContext.Request.IsAjaxRequest()) //Ajax请求
                    {
                        filterContext.Result = new JsonResult()
                        {
                            Data = new AjaxResult()
                            {
                                Success = false,
                                Message = "对不起,当前功能你没有权限访问"
                            }
                        };
                    }
                    else //非Ajax请求
                    {
                        filterContext.Result = new RedirectResult("/Home/UnAuthorize");
                    }
                }
            }
        }

        /// <summary>
        /// 没有Session的响应
        /// </summary>
        /// <param name="filterContext"></param>
        private static void ResponseResult(AuthorizationContext filterContext)
        {
            if (filterContext.HttpContext.Request.IsAjaxRequest()) //Ajax请求
            {
                filterContext.Result = new JsonResult()
                {
                    Data = new AjaxResult()
                    {
                        Success = false,
                        Message = "没有登录,无法获取数据"
                    }
                };
            }
            else //非Ajax请求
            {
                filterContext.Result = new RedirectResult("Account/Login");
            }
        }

2,具体在控制器引用权限认证方法

文章来源:https://blog.csdn.net/totos11111/article/details/135043586
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。