自定义授权属性不起作用

时间:2013-04-24 05:01:54

标签: asp.net-mvc-4

我在类中添加了自定义authorize属性,以检查登录用户是否为admin。但这不起作用。这是我的代码

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

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

1 个答案:

答案 0 :(得分: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.
    }
}