使用英语阅读

通过


RoleProvider.IsUserInRole(String, String) 方法

定义

获取一个值,该值指示指定用户是否属于已配置的 applicationName 的指定角色。

public abstract bool IsUserInRole(string username, string roleName);

参数

username
String

要搜索的用户名。

roleName
String

作为搜索范围的角色。

返回

如果指定用户属于已配置的 applicationName 的指定角色,则为 true;否则为 false

示例

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

public override bool IsUserInRole(string username, string rolename)
{
  if (username == null || username == "")
    throw new ProviderException("User name cannot be empty or null.");
  if (rolename == null || rolename == "")
    throw new ProviderException("Role name cannot be empty or null.");

  bool userIsInRole = false;

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

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

  try
  {
    conn.Open();

    int numRecs = (int)cmd.ExecuteScalar();

    if (numRecs > 0)
    {
      userIsInRole = true;
    }
  }
  catch (OdbcException)
  {
    // Handle exception.
  }
  finally
  {
    conn.Close();      
  }

  return userIsInRole;
}

注解

方法 IsUserInRoleIsUserInRole 类的 Roles 方法调用,以确定当前登录用户是否与所配置的 ApplicationName数据源中的角色相关联。

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

如果指定的角色名称为 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

另请参阅