我创建了一个自定义的角色基础授权属性。我的想法是,当角色名称为“员工”的用户登录时,不应允许通过 URL 访问“管理员”页面。但是当我实现[MyRoleAuthorization]
in Employee 控制器并登录时,错误显示“这个网页有一个重定向循环”。这是代码[MyRoleAuthorization]
public class MyRoleAuthorization : AuthorizeAttribute
{
string isAuthorized;
private string AuthorizeUser(AuthorizationContext filterContext)
{
if (filterContext.RequestContext.HttpContext != null)
{
var context = filterContext.RequestContext.HttpContext;
if (Convert.ToString(context.Session["RoleName"]) == "Admin")
{
isAuthorized = "Admin";
}
else if (Convert.ToString(context.Session["RoleName"]) == "Employee")
{
isAuthorized = "Employee";
}
else if (Convert.ToString((context.Session["RoleName"])) == "Customer")
{
isAuthorized = "Customer";
}
else
{
throw new ArgumentException("filterContext");
}
}
return isAuthorized;
}
public override void OnAuthorization(AuthorizationContext filterContext)
{
if (filterContext == null)
throw new ArgumentException("filterContext");
if (AuthorizeUser(filterContext) == "Admin")
{
filterContext.Result = new RedirectToRouteResult
(new RouteValueDictionary(new { controller = "Admin" }));
}
else if (AuthorizeUser(filterContext) == "Employee")
{
filterContext.Result = new RedirectToRouteResult
(new RouteValueDictionary(new { controller = "Employee" }));
}
else if (AuthorizeUser(filterContext) == "Customer")
{
filterContext.Result = new RedirectToRouteResult
(new RouteValueDictionary(new { controller = "Customer" }));
}
}
}
}
我的员工控制器看起来像这样
[MyRoleAuthorization]
public ActionResult Index()
{
var employee = db.Employee.Include(e => e.User);
return View(employee.ToList());
}
你能帮我么。