0

Asp.net MVC 使用什么数据源来查看用户是否属于哪个角色。以及如何更改它以使其与我自己的数据库表一起使用(当我编写[Autorize(Roles="admin")]它时,如果用户处于角色中,则检查表)

4

1 回答 1

4

Asp.net MVC 使用什么数据源来查看用户是否属于哪个角色。

它使用RoleProvider在您的 web.config 中配置的内容。如果您想使用自定义表,您可以custom role provider通过从RoleProvider类继承并实现抽象成员来编写。该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()
{
    ...
}
于 2013-02-17T14:13:17.907 回答