我在类中添加了自定义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" }));
}
}
}
在从会话中获取用户数据以检查用户是否为管理员以及他是否为管理员然后重定向到访问被拒绝页面时,这里做了什么。但这不起作用。对于每个用户,页面都会被查看。
答案 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.
}
}