111*_*110 9 c# asp.net-mvc custom-attributes asp.net-mvc-3
我想保护控制器操作,以便只有角色为"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");
}
}
Run Code Online (Sandbox Code Playgroud)
请注意,我在这里硬编码了"Admin".
我希望这是动态的.
这项工作现在:
[CustomAuthorize]
public ActionResult RestrictedArea()...
Run Code Online (Sandbox Code Playgroud)
但是我想要这样的东西:
[CustomAuthorize(Roles = "Admin")]
public ActionResult RestrictedArea()
Run Code Online (Sandbox Code Playgroud)
Zbi*_*iew 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);
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
16143 次 |
| 最近记录: |