[英]How to use Custom AuthorizeAttribute for controller utilizing parameter value?
[英]How to add 'pass parameter' to custom AuthorizeAttribute
我想保护控制器操作,以便只有角色为“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()
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);
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.