đang tốt hơn với việc thêm một lớp con AuthorizeRole.cs
[AttributeUsage(AttributeTargets.Method | AttributeTargets.Class, Inherited = true, AllowMultiple = true)]
class AuthorizeRoleAttribute : AuthorizeAttribute
{
public AuthorizeRoleAttribute(params Rolenames[] roles)
{
this.Roles = string.Join(",", roles.Select(r => Enum.GetName(r.GetType(), r)));
}
protected override void HandleUnauthorizedRequest(System.Web.Mvc.AuthorizationContext filterContext)
{
if (filterContext.HttpContext.Request.IsAuthenticated)
{
filterContext.Result = new RedirectToRouteResult(
new RouteValueDictionary {
{ "action", "Unauthorized" },
{ "controller", "Home" },
{ "area", "" }
}
);
//base.HandleUnauthorizedRequest(filterContext);
}
else
{
filterContext.Result = new RedirectToRouteResult(
new RouteValueDictionary {
{ "action", "Login" },
{ "controller", "Account" },
{ "area", "" },
{ "returnUrl", HttpContext.Current.Request.Url }
}
);
}
}
}
Làm thế nào để sử dụng
[AuthorizeRole(Rolenames.Admin,Rolenames.Member)]
public ActionResult Index()
{
return View();
}
Nguồn
2016-01-27 07:20:44
Vui lòng thay đổi câu trả lời được chấp nhận cho câu hỏi này. Người có câu trả lời hiện đang được chấp nhận đã chỉnh sửa câu trả lời cho biết rằng anh đã sai. –