0

我在类中添加了自定义授权属性以检查登录用户是否为管理员。但这行不通。这是我的代码

[AdminAuthorization]
public class UsersController : Controller
{
    public ActionResult Index()
    {
        return View();
    }
}

public sealed class AdminAuthorizationAttribute : AuthorizeAttribute
{
    protected override void HandleUnauthorizedRequest(AuthorizationContext filterContext)
    {
        if(!UserSessionHelper.Instance.IsValid && !UserSessionHelper.Instance.Data.IsAdmin)
        {
            filterContext.Result = new RedirectToRouteResult(new RouteValueDictionary(new { controller = "Error", action = "AccessDenied" }));
        }
    }
}

在这里从会话中获取用户数据以检查用户是否是管理员以及如果他不是管理员则重定向到访问被拒绝页面时正在做什么。但这不起作用。对于每个用户,该页面都会被查看。

4

1 回答 1

2

试试这个,根据我的理解,你需要覆盖OnAuthorization函数。

改变你AdminAuthorizationAttribute的班级

public sealed class AdminAuthorizationAttribute : AuthorizeAttribute
{
    public override void OnAuthorization(AuthorizationContext filterContext)
    {
        //Called when a process requests authorization.
        if (!UserSessionHelper.Instance.IsValid && !UserSessionHelper.Instance.Data.IsAdmin)
        {
            filterContext.Result = new RedirectToRouteResult(new RouteValueDictionary(new { controller = "Error", action = "AccessDenied" }));
            return;
        }
        base.OnAuthorization(filterContext);
    }

    protected override void HandleUnauthorizedRequest(AuthorizationContext filterContext)
    {
        //Processes HTTP requests that fail authorization.
    }
}
于 2013-04-24T05:19:24.780 回答