Asp.net MVC用来查看用户是否属于哪个角色的数据源是什么。我如何更改它,使其与我自己的数据库表一起工作(当我编写[Autorize(Roles="admin")]
时,它会在表中检查用户是否在该角色中)
发布于 2013-02-17 22:13:18
Asp.net MVC用来查看用户是否属于哪个角色的数据源是什么。
它使用在web.config中配置的RoleProvider
。如果希望使用定制表,可以通过继承RoleProvider
类并实现抽象成员来编写custom role provider
。IsUserInRole
方法是您应该始终实现的方法,因为它将在本例中使用:
public class MyRoleProvider: RoleProvider
{
public override bool IsUserInRole(string username, string roleName)
{
// go and hit your custom datasource to verify if the user
// is in the required role and return true or false from this
// method
...
}
}
然后,您可以在web.config中注册您的自定义角色提供程序,以替换默认的提供程序:
<system.web>
...
<roleManager enabled="true" defaultProvider="MyRoleProvider">
<providers>
<add name="MyRoleProvider" type="Mynamespace.MyRoleProvider" />
</providers>
</roleManager>
</system.web>
如果您不想使用任何提供程序(从您的previous question
判断似乎就是这样),那么您应该编写一个自定义Authorize
属性,它根本不使用角色提供程序,而是使用您自己的一些自定义代码:
public class MyAuthorizeAttribute : AuthorizeAttribute
{
protected override bool AuthorizeCore(HttpContextBase httpContext)
{
if (!httpContext.User.Identity.IsAuthenticated)
{
// no user is authenticated => no need to go any further
return false;
}
// at this stage we have an authenticated user
string username = httpContext.User.Identity.Name;
return IsInRole(username, this.Roles);
}
private bool static IsInRole(string username, string roles)
{
// the username parameter will contain the currently authenticated user
// the roles parameter will contain the string specified in the attribute
// (for example "admin")
// so here go and hit your custom tables and verify if the user is
// in the required role
...
}
}
最后,使用这个自定义属性来修饰您的控制器操作,而不是依赖于基于角色提供程序的默认属性:
[MyAutorize(Roles = "admin")]
public ActionResult Index()
{
...
}
https://stackoverflow.com/questions/14921897
复制相似问题