我創建了一個自定義的角色基授權屬性。我的想法是,當角色名稱爲「employee」的用戶登錄不應該被允許通過URL訪問「admin」頁面。但是,當我在員工控制器中執行[MyRoleAuthorization]
並登錄時,錯誤顯示「此網頁具有重定向循環」。 這是[MyRoleAuthorization]
具有角色的MVC 4中的自定義授權屬性
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());
}
你能幫幫我。