我的自定义授权属性总是重定向到未授权页面

My Custom Authorize Attribute Always Redirects to Un authroized page

我正在为一项要求编写自定义授权属性。

根据要求,我需要为该特定操作方法传递所有允许的角色,如下所示。

    [MyAuthorize("Admin,Reviewer")]
    public ActionResult GetFXSelldownSummaryData()
    {
        var model = (new FXSelldownSummaryBLL()).GetFXSelldownSummaryData();
        return View(model);
    }

当用户登录时,登录的用户角色应该与所有允许的角色进行比较(在上面的代码中,所有允许的角色是AdminReviewer)。如果角色匹配,则用户可以看到视图,否则页面应导航到未授权页面。

我已经编写了如下自定义属性,一切正常,但我以所有请求的未授权访问页面结束。

谁能帮忙找出并解决问题![​​=14=]

namespace MyRequirement
{

    public class MyAuthorizeAttribute : AuthorizeAttribute
    {
        readonly string allowedRoles;
        public MyAuthorizeAttribute(string allowedRoles)
        {
            this.allowedRoles = allowedRoles;
        }

        public System.Collections.Generic.List<string> AllowedRoles
        {
            get
            {
                return this.allowedRoles.Split(',').ToList();
            }
        }

        private bool AuthorizeRole(AuthorizationContext filterContext)
        {
            var context = filterContext.RequestContext.HttpContext;
            PnLUserDetails userDetails = System.Web.HttpContext.Current.Session["PnLUserDetails"] as PnLUserDetails;
            string loggedInUserRole = userDetails.Role;
            if (AllowedRoles.Contains(loggedInUserRole))
                return true;
            return false;
        }

        public override void OnAuthorization(AuthorizationContext filterContext)
        {
            base.OnAuthorization(filterContext);
            if (filterContext == null)
                throw new ArgumentException("filterContext");
            bool authStatus = AuthorizeRole(filterContext);
            if(!authStatus)
            {
                filterContext.Result = new HttpUnauthorizedResult();
                return;
            }
        }
    }
}

删除对

的调用
base.OnAuthorization(filterContext);

像这样更改代码

    public override void OnAuthorization(AuthorizationContext filterContext)
    {
        // This line is not needed, you are handling the authorization
        // This is the line that will give you the unauthorized access by default
        // base.OnAuthorization(filterContext);
        if (filterContext == null)
            throw new ArgumentException("filterContext");
        bool authStatus = AuthorizeRole(filterContext);
        if(!authStatus)
        {
            filterContext.Result = new HttpUnauthorizedResult();
            return;
        }
    }