角色管理没有提供者?

Ash*_*OoO 3 .net asp.net asp.net-membership roleprovider

在我的应用程序中,我需要检查loggind用户的角色,以确定用户是否可以看到某些控件

首先我使用MS的loginview模板,但由于我没有用户db,因此我没有角色db所以我无法添加角色提供程序,所以我无法使用Role类来检查用户\角色

在我的情况下,我有一个会话,其中包含用户信息和他拥有的角色,我需要对这些角色进行检查,以设置将为用户启用哪个控件,但标准方式是"在类或代码中使用.net"

Rob*_*Rob 7

如果要使用部分asp.net成员身份/身份验证/授权服务,则需要实现自定义角色提供程序以执行角色成员身份检查.

要做的第一件事是创建一个继承自的类,System.Web.Security.RoleProvider其中听起来像您最初关心的方法是:

  • FindUsersInRole
  • GetRolesForUser
  • GetUsersInRole
  • 的isUserInRole

所以,你最终会得到类似的东西:

using System; 
using System.Collections.Generic; 
using System.Linq; 
using System.Web; 
using System.Web.Security;

public class MyCustomRoleProvider : RoleProvider
{
    public override string[] FindUsersInRole(string roleName, string usernameToMatch)
    {
    }

    public override string[] GetRolesForUser(string username)
    {
    }

    public override string[] GetUsersInRole(string roleName)
    {
    }

    public override bool IsUserInRole(string username, string roleName)
    {
        return GetUsersInRole(roleName).Contains(username);
    }
}
Run Code Online (Sandbox Code Playgroud)

注意:Visual Studio将显示许多方法,例如GetAllRoles使用a throws new NotImplementedException(),但我之前编写了"最小"角色提供程序,只需要实现上面列出的方法.这是针对"只读"角色,但Web应用程序没有更新它们.

然后,您需要将roleManager元素添加到web.config文件中system.web,如下所示:

<roleManager defaultProvider="NameOfYourRoleProvider" enabled="true">
    <providers>
        <clear />
         <add name="NameOfYourRoleProvider" type="Namespace.To.Your.Class.And.Class.Name, Name.Of.Assembly.Containing.Your.RoleProvider" />
    </providers>
</roleManager>
Run Code Online (Sandbox Code Playgroud)

要记住的一件事是,RoleProvider实例是由底层的asp.net基础设施创建的,所以你需要通过经过HttpContext.Current.Session(并HttpContext.Current在使用它之前检查非空)来访问会话数据,这将需要一个using System.Web;在您的提供商的代码中.