ClientRoleProvider.IsUserInRole(String, String) Método

Definição

Obtém um valor que indica se o usuário especificado está na função especificada para a função especificada.Gets a value indicating whether the specified user is in the specified role.

public:
 override bool IsUserInRole(System::String ^ username, System::String ^ roleName);
public override bool IsUserInRole (string username, string roleName);
override this.IsUserInRole : string * string -> bool
Public Overrides Function IsUserInRole (username As String, roleName As String) As Boolean

Parâmetros

username
String

O nome de usuário.The name of the user.

roleName
String

O nome da função.The name of the role.

Retornos

Boolean

true se o usuário especificado está na função especificada; false se o usuário especificado não está autenticado ou não está na função especificada.true if the specified user is in the specified role; false if the specified user is not authenticated or is not in the specified role.

Exceções

username é Empty ou null.username is Empty or null.

- ou --or- username não é o nome de usuário do usuário atual autenticado.username is not the user name of the current, authenticated user.

O usuário não está mais autenticado.The user is no longer authenticated.

- ou --or-

O serviço de funções não está disponível.The roles service is not available.

Exemplos

O código de exemplo a seguir demonstra como acessar esse método diretamente para determinar se o usuário está em uma função específica.The following example code demonstrates how to access this method directly to determine whether the user is in a particular role. Esse código primeiro testa se o logon do usuário expirou.This code first tests whether the user login has expired. Uma ClientRoleProvider referência explícita é necessária para chamar o GetRolesForUser método, portanto, a mesma referência é usada para chamar o IsUserInRole método.An explicit ClientRoleProvider reference is required to call the GetRolesForUser method, so the same reference is used to call the IsUserInRole method. Se o usuário estiver na função "gerente", esse código chamará um PerformManagerTask método, que não é fornecido.If the user is in the "manager" role, this code calls a PerformManagerTask method, which is not provided.

private void AttemptManagerTask()
{
    System.Security.Principal.IIdentity identity =
        System.Threading.Thread.CurrentPrincipal.Identity;

    // Return if the authentication type is not "ClientForms". 
    // This indicates that the user is logged out.
    if (!identity.AuthenticationType.Equals("ClientForms")) return;

    try
    {
        ClientRoleProvider provider =
            (ClientRoleProvider)System.Web.Security.Roles.Provider;
        String userName = identity.Name;

        // Determine whether the user login has expired by attempting
        // to retrieve roles from the service. Call the ResetCache method
        // to ensure that the roles are retrieved from the service. If no 
        // roles are returned, then the login has expired. This assumes 
        // that every valid user has been assigned to one or more roles.
        provider.ResetCache();
        String[] roles = provider.GetRolesForUser(userName);
        if (roles.Length == 0)
        {
            MessageBox.Show(
                "Your login has expired. Please log in again to access " +
                "the roles service.", "Attempting to access user roles...");

            // Call ValidateUser with empty strings in order to 
            // display the login dialog box configured as a 
            // credentials provider.
            if (!System.Web.Security.Membership.ValidateUser(
                String.Empty, String.Empty))
            {
                MessageBox.Show("Unable to authenticate. " +
                    "Cannot retrieve user roles.", "Not logged in",
                    MessageBoxButtons.OK, MessageBoxIcon.Error);
                return;
            }
        }

        if (provider.IsUserInRole(userName, "manager"))
        {
            PerformManagerTask();
        }
    }
    catch (System.Net.WebException)
    {
        MessageBox.Show(
            "Unable to access the remote service. " +
            "Cannot retrieve user roles.", "Warning",
            MessageBoxButtons.OK, MessageBoxIcon.Warning);
    }
}
Private Sub AttemptManagerTask()

    Dim identity As System.Security.Principal.IIdentity = _
        System.Threading.Thread.CurrentPrincipal.Identity

    ' Return if the authentication type is not "ClientForms". 
    ' This indicates that the user is logged out.
    If Not identity.AuthenticationType.Equals("ClientForms") Then Return

    Try

        Dim provider As ClientRoleProvider = _
            CType(System.Web.Security.Roles.Provider, ClientRoleProvider)
        Dim userName As String = identity.Name

        ' Determine whether the user login has expired by attempting
        ' to retrieve roles from the service. Call the ResetCache method
        ' to ensure that the roles are retrieved from the service. If no 
        ' roles are returned, then the login has expired. This assumes 
        ' that every valid user has been assigned to one or more roles.
        provider.ResetCache()
        Dim roles As String() = provider.GetRolesForUser(userName)
        If roles.Length = 0 Then

            MessageBox.Show( _
                "Your login has expired. Please log in again to access " & _
                "the roles service.", "Attempting to access user roles...")

            ' Call ValidateUser with empty strings in order to 
            ' display the login dialog box configured as a 
            ' credentials provider.
            If Not System.Web.Security.Membership.ValidateUser( _
                String.Empty, String.Empty) Then

                MessageBox.Show("Unable to authenticate. " & _
                    "Cannot retrieve user roles.", "Not logged in", _
                    MessageBoxButtons.OK, MessageBoxIcon.Error)
                Return

            End If

        End If

        If provider.IsUserInRole(userName, "manager") Then
            PerformManagerTask()
        End If

    Catch ex As System.Net.WebException

        MessageBox.Show( _
            "Unable to access the remote service. " & _
            "Cannot retrieve user roles.", "Warning", _
            MessageBoxButtons.OK, MessageBoxIcon.Warning)

    End Try

End Sub

Comentários

Você pode determinar se um usuário autenticado está em uma função específica chamando o IsInRole método do IPrincipal retornado pela static Thread.CurrentPrincipal propriedade.You can determine whether an authenticated user is in a particular role by calling the IsInRole method of the IPrincipal returned by the static Thread.CurrentPrincipal property. Para aplicativos configurados para usar serviços de aplicativos cliente, essa propriedade retorna um ClientRolePrincipal.For applications configured to use client application services, this property returns a ClientRolePrincipal. Como essa classe implementa a interface IPrincipal, você não precisa referenciá-la explicitamente.Because this class implements the IPrincipal interface, you do not need to reference it explicitly. O ClientRolePrincipal.IsInRole método chama internamente o IsUserInRole método.The ClientRolePrincipal.IsInRole method internally calls the IsUserInRole method. O IsUserInRole método usa o GetRolesForUser método para determinar se o usuário indicado por username está na função indicada por roleName .The IsUserInRole method uses the GetRolesForUser method to determine whether the user indicated by username is in the role indicated by roleName.

O provedor de serviços armazena em cache as informações de função sobre o sistema de arquivos local para evitar chamadas de serviço desnecessárias.The service provider caches role information about the local file system to avoid unnecessary service calls. Para obter mais informações, consulte a ClientRoleProvider visão geral da classe.For more information, see the ClientRoleProvider class overview.

Aplica-se a

Confira também