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

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

 public class CustomAuthorizeAttribute : FilterAttribute, IAuthorizationFilter
    {
        /// 
        /// 如果需要验证权限的时候,就执行进来
        /// 
        /// 
        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> tupMen = currentUser.TupMenue;

                List 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");
                    }
                }
            }
        }

        /// 
        /// 没有Session的响应
        /// 
        /// 
        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,具体在控制器引用权限认证方法

ASP.NET MVC实战之权限拦截Authorize使用_第1张图片

ASP.NET MVC实战之权限拦截Authorize使用_第2张图片

你可能感兴趣的:(Asp.net,Mvc,Asp.Net,mvc,c#,asp.net)