首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >如何将filter属性中的角色与我的数据库关联?

如何将filter属性中的角色与我的数据库关联?
EN

Stack Overflow用户
提问于 2013-02-17 22:07:25
回答 1查看 2.4K关注 0票数 0

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

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2013-02-17 22:13:18

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

它使用在web.config中配置的RoleProvider。如果希望使用定制表,可以通过继承RoleProvider类并实现抽象成员来编写custom role providerIsUserInRole方法是您应该始终实现的方法,因为它将在本例中使用:

代码语言:javascript
运行
复制
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中注册您的自定义角色提供程序,以替换默认的提供程序:

代码语言:javascript
运行
复制
<system.web>
    ...
    <roleManager enabled="true" defaultProvider="MyRoleProvider"> 
        <providers> 
            <add name="MyRoleProvider" type="Mynamespace.MyRoleProvider" /> 
        </providers> 
    </roleManager>
</system.web>

如果您不想使用任何提供程序(从您的previous question判断似乎就是这样),那么您应该编写一个自定义Authorize属性,它根本不使用角色提供程序,而是使用您自己的一些自定义代码:

代码语言:javascript
运行
复制
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
        ... 
    }
}

最后,使用这个自定义属性来修饰您的控制器操作,而不是依赖于基于角色提供程序的默认属性:

代码语言:javascript
运行
复制
[MyAutorize(Roles = "admin")]
public ActionResult Index()
{
    ...
}
票数 4
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/14921897

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档