RoleProvider.IsUserInRole(String, String) Method

Definition

Gets a value indicating whether the specified user is in the specified role for the configured applicationName.

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

Parameters

username
String

The user name to search for.

roleName
String

The role to search in.

Returns

true if the specified user is in the specified role for the configured applicationName; otherwise, false.

Examples

The following code example shows a sample implementation of the IsUserInRole method.

C#
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;
}

Remarks

The IsUserInRole method is called by the IsUserInRole method of the Roles class to determine whether the current logged-on user is associated with a role from the data source for the configured ApplicationName.

If the specified user name is null or is an empty string, we recommend that your provider throw an exception.

If the specified role name is null or is an empty string, we recommend that your provider throw an exception.

Applies to

Product Versions
.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

See also