mvc 自定义 AuthorizeAttribute 验证逻辑

public class AuthorizationFilterAttribute : AuthorizeAttribute
    {
        Dictionary<string, string> roles = new Dictionary<string, string>() { 
        {"1","/Home/Index"},
        {"2",""},
        };

        /// <summary>
        /// 自定义验证逻辑 返回false时 才会执行HandleUnauthorizedRequest
        /// </summary>
        /// <param name="httpContext"></param>
        /// <returns></returns>
        protected override bool AuthorizeCore(HttpContextBase httpContext)
        {
            var id = Convert.ToString(httpContext.Request.QueryString["id"]);

            if (id == null || !roles.ContainsKey(id))
                return false;

            string controller = Convert.ToString(httpContext.Request.RequestContext.RouteData.Values["controller"]);
            string action = Convert.ToString(httpContext.Request.RequestContext.RouteData.Values["action"]);

            return string.Compare(roles[id], string.Format("/{0}/{1}", controller, action), true) == 0;
        }

        public override void OnAuthorization(AuthorizationContext filterContext)
        {
            base.OnAuthorization(filterContext);
        }

        protected override void HandleUnauthorizedRequest(AuthorizationContext filterContext)
        {
            UrlHelper url = new UrlHelper(filterContext.HttpContext.Request.RequestContext);
            filterContext.HttpContext.Response.StatusCode = (int)HttpStatusCode.Unauthorized;

            filterContext.Result = new RedirectResult(url.Action("login", "home"));
        }
    }

 

public static void RegisterGlobalFilters(GlobalFilterCollection filters)
        {
            filters.Add(new AuthorizationFilterAttribute());
            filters.Add(new HandleErrorAttribute());
        }

  

filterContext.Result只要不为空Action就会终止。直接响应请求。
posted on 2015-10-30 17:38  梦回周公  阅读(646)  评论(0编辑  收藏  举报