问题描述
什么Asp.net MVC使用以查看是否该用户是其中角色数据源。我怎么可以改变它,这样它与我自己的数据库表的工作原理(当我写 [Autorize(角色=管理员)]
它会检查表中,如果用户在角色)
It uses the RoleProvider
that is configured in your web.config. If you want to use custom tables you could write a custom role provider
by inheriting from the RoleProvider
class and implementing the abstract members. The IsUserInRole
method is the one that you should always implement because that's what will be used in this case:
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
...
}
}
Then you could register your custom role provider in web.config in order to replace the default one:
<system.web>
...
<roleManager enabled="true" defaultProvider="MyRoleProvider">
<providers>
<add name="MyRoleProvider" type="Mynamespace.MyRoleProvider" />
</providers>
</roleManager>
</system.web>
And if you don't want to be using any providers (judging from your previous question
that seems to be the case) then you should write a custom Authorize
attribute which is not using a role provider at all but is using some custom code of yours:
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
...
}
}
and finally decorate your controller action with this custom attribute instead of relying on the default one which is based on the role provider:
[MyAutorize(Roles = "admin")]
public ActionResult Index()
{
...
}
这篇关于如何与过滤器属性的角色与我的数据库?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!