Roles.Provider 属性

定义

获取应用程序的默认角色提供程序。

C#
public static System.Web.Security.RoleProvider Provider { get; }

属性值

应用程序的默认角色提供程序,作为继承 RoleProvider 抽象类的类公开。

例外

未启用角色管理。

示例

下面的代码示例将默认角色提供程序强制转换为 , WindowsTokenRoleProvider 并检查当前登录的用户是否处于管理员角色中,然后允许用户查看应用程序的角色设置。 有关启用角色管理的 Web.config 文件的示例,请参阅 WindowsTokenRoleProvider

ASP.NET (C#)
<%@ Page Language="C#" %>
<%@ Import Namespace="System.Web.Security" %>
<%@ Import Namespace="System.Security.Principal" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
    "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<script runat="server">

string[] rolesArray;

public void Page_Load()
{
  Msg.Text = "";

  WindowsPrincipal p = (WindowsPrincipal)System.Threading.Thread.CurrentPrincipal;

  if (!p.IsInRole(WindowsBuiltInRole.Administrator))
  {
    Msg.Text = "You are not authorized to view user roles.";
    return;
  }


  // Bind roles to GridView.

  try
  {
    rolesArray = Roles.GetRolesForUser(User.Identity.Name);
  }
  catch (HttpException e)
  {
    Msg.Text = "There is no current logged on user. Role membership cannot be verified.";
    return;
  }

  UserRolesGrid.DataSource = rolesArray;
  UserRolesGrid.DataBind();

  UserRolesGrid.Columns[0].HeaderText = "Roles for " + User.Identity.Name;
}

</script>
<html xmlns="http://www.w3.org/1999/xhtml" >
<head>
<title>Sample: View User Roles</title>
</head>
<body>

<form runat="server" id="PageForm">

  <h3>View User Roles</h3>

  <asp:Label id="Msg" ForeColor="maroon" runat="server" /><br />

  <table border="0" cellspacing="4">
    <tr>
      <td valign="top"><asp:GridView runat="server" CellPadding="4" id="UserRolesGrid" 
                                     AutoGenerateColumns="false" Gridlines="None" 
                                     CellSpacing="0" >
                         <HeaderStyle BackColor="navy" ForeColor="white" />
                         <Columns>
                           <asp:TemplateField HeaderText="Roles" >
                             <ItemTemplate>
                               <%# Container.DataItem.ToString() %>
                             </ItemTemplate>
                           </asp:TemplateField>
                         </Columns>
                       </asp:GridView></td>
    </tr>
  </table>

</form>

</body>
</html>

注解

属性 Provider 使你能够直接引用应用程序的默认角色提供程序。 这通常用于访问不属于抽象类的角色提供程序的 RoleProvider 自定义成员。

例如, WindowsTokenRoleProvider 类包含 方法的 IsUserInRole 重载,使你能够通过使用 WindowsBuiltInRole 枚举值来确定用户是否处于通用 Windows 角色中。 可以使用 Provider 属性获取对应用程序的 类的引用WindowsTokenRoleProvider,并且可以强制转换为 WindowsTokenRoleProvider 以引用IsUserInRole重载。

如果为应用程序配置了多个角色提供程序,则可以使用 Providers 集合访问不同的角色提供程序。

适用于

产品 版本
.NET Framework 2.0, 3.0, 3.5, 4.0, 4.5, 4.5.1, 4.5.2, 4.6, 4.6.1, 4.6.2, 4.7, 4.7.1, 4.7.2, 4.8, 4.8.1

另请参阅