使用英语阅读

通过


RoleProvider.GetRolesForUser(String) 方法

定义

获取已配置的 applicationName 中指定用户所属的角色的列表。

public abstract string[] GetRolesForUser(string username);

参数

username
String

要为其返回角色列表的用户。

返回

String[]

一个字符串数组,其中包含已配置的 applicationName 中指定用户所属的所有角色的名称。

示例

下面的代码示例演示 方法的示例 GetRolesForUser 实现。

public override string[] GetRolesForUser(string username)
{
  if (username == null || username == "")
    throw new ProviderException("User name cannot be empty or null.");

  string tmpRoleNames = "";

  OdbcConnection conn = new OdbcConnection(connectionString);
  OdbcCommand cmd = new OdbcCommand("SELECT Rolename FROM UsersInRoles "  +
                                    " WHERE Username = ? AND ApplicationName = ?", conn);

  cmd.Parameters.Add("@Username", OdbcType.VarChar, 255).Value = username;
  cmd.Parameters.Add("@ApplicationName", OdbcType.VarChar, 255).Value = ApplicationName;

  OdbcDataReader reader = null;

  try
  {
    conn.Open();

    reader = cmd.ExecuteReader();

    while (reader.Read())
    {
      tmpRoleNames += reader.GetString(0) + ",";
    }
  }
  catch (OdbcException)
  {
    // Handle exception.
  }
  finally
  {
    if (reader != null) { reader.Close(); }
    conn.Close();      
  }

  if (tmpRoleNames.Length > 0)
  {
    // Remove trailing comma.
    tmpRoleNames = tmpRoleNames.Substring(0, tmpRoleNames.Length - 1);
    return tmpRoleNames.Split(',');
  }

  return new string[0];
}

注解

GetRolesForUserGetRolesForUser 类的 Roles 方法调用,以从数据源检索与指定用户关联的角色名称。 仅检索已配置 ApplicationName 的角色。

如果所配置的 applicationName的指定用户不存在任何角色,我们建议提供程序返回不带元素的字符串数组。

如果指定的用户名为 null 或为空字符串,建议提供程序引发异常。

适用于

产品 版本
.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

另请参阅