我想保护控制器操作,以便只有角色为“Admin”的用户才能进入。
我根本没有使用角色/会员提供商。一切都是自定义的
到目前为止,我做到了这一点:
public class CustomAuthorizeAttribute : AuthorizeAttribute
{
protected override bool AuthorizeCore(HttpContextBase httpContext)
{
var isAuthorized = base.AuthorizeCore(httpContext);
if (!isAuthorized)
return false;
string username = httpContext.User.Identity.Name;
UserRepository repo = new UserRepository();
return repo.IsUserInRole(username, "Admin");
}
}
请注意,我在这里硬编码了“Admin” 我希望这是动态的 现在这项工作:
[CustomAuthorize]
public ActionResult RestrictedArea()...
但我想要这样的事情:
[CustomAuthorize(Roles = "Admin")]
public ActionResult RestrictedArea()
答案 0 :(得分:20)
AuthorizeAttribute
已有Roles
属性,可用于此目的:
public class CustomAuthorizeAttribute : AuthorizeAttribute
{
protected override bool AuthorizeCore(HttpContextBase httpContext)
{
var isAuthorized = base.AuthorizeCore(httpContext);
if (!isAuthorized)
{
return false;
}
string username = httpContext.User.Identity.Name;
UserRepository repo = new UserRepository();
return repo.IsUserInRole(username, this.Roles);
}
}