ClientRolePrincipal.IsInRole(String) Método
Definição
Obtém um valor que indica se o usuário representado por ClientRolePrincipal está na função especificada.Gets a value indicating whether the user represented by the ClientRolePrincipal is in the specified role.
public:
virtual bool IsInRole(System::String ^ role);
public bool IsInRole (string role);
abstract member IsInRole : string -> bool
override this.IsInRole : string -> bool
Public Function IsInRole (role As String) As Boolean
Parâmetros
- role
- String
A função a verificar.The role to check.
Retornos
true se o usuário está na função especificada; false se o usuário não está autenticado ou não está na função especificada.true if the user is in the specified role; false if the user is not in the specified role or is not authenticated.
Implementações
Exemplos
O código de exemplo a seguir demonstra como usar esse método para exibir um botão somente quando o usuário está na função "gerente".The following example code demonstrates how to use this method to display a button only when the user is in the "manager" role. Este exemplo requer um Button nome managerOnlyButton com um Visible valor de propriedade inicial de false .This example requires a Button named managerOnlyButton with an initial Visible property value of false.
private void DisplayButtonForManagerRole()
{
try
{
ClientRolePrincipal rolePrincipal =
System.Threading.Thread.CurrentPrincipal
as ClientRolePrincipal;
if (rolePrincipal != null && rolePrincipal.IsInRole("manager"))
{
managerOnlyButton.Visible = true;
}
}
catch (System.Net.WebException)
{
MessageBox.Show("Unable to access the roles service.",
"Warning", MessageBoxButtons.OK, MessageBoxIcon.Warning);
}
}
Private Sub DisplayButtonForManagerRole()
Try
Dim rolePrincipal As ClientRolePrincipal = TryCast( _
System.Threading.Thread.CurrentPrincipal, ClientRolePrincipal)
If rolePrincipal IsNot Nothing And _
rolePrincipal.IsInRole("manager") Then
managerOnlyButton.Visible = True
End If
Catch ex As System.Net.WebException
MessageBox.Show("Unable to access the role service.", _
"Warning", MessageBoxButtons.OK, MessageBoxIcon.Warning)
End Try
End Sub
Comentários
Normalmente, você chamará o IsInRole método do IPrincipal retornado pela static Thread.CurrentPrincipal propriedade.Normally, you will call the IsInRole method of the IPrincipal returned by the static Thread.CurrentPrincipal property. No entanto, você pode converter o CurrentPrincipal valor da propriedade em uma ClientRolePrincipal referência para chamar esse método explicitamente, como demonstrado na seção de exemplo.However, you can cast the CurrentPrincipal property value to a ClientRolePrincipal reference to call this method explicitly, as demonstrated in the Example section.
O método IsInRole sempre retornará false se o logon do usuário tiver expirado.The IsInRole method will always return false if the user login has expired. Isso não ocorrerá se seu aplicativo chamar o IsInRole método uma vez logo após a autenticação.This will not occur if your application calls the IsInRole method one time shortly after authentication. Se seu aplicativo precisar recuperar funções de usuário em outros momentos, convém adicionar código para revalidar usuários cujo logon tiver expirado.If your application must retrieve user roles at other times, you might want to add code to revalidate users whose login has expired. Se todos os usuários válidos forem atribuídos às funções, você poderá determinar se o logon expirou chamando o método ClientRoleProvider.GetRolesForUser.If all valid users are assigned to roles, you can determine whether the login has expired by calling the ClientRoleProvider.GetRolesForUser method. Se nenhuma função tiver sido retornada, isso significará que o logon expirou.If no roles are returned, the login has expired. Para ver um exemplo dessa funcionalidade, consulte o método GetRolesForUser.For an example of this functionality, see the GetRolesForUser method. Essa funcionalidade somente será necessária se você tiver selecionado Exigir que os usuários façam logon novamente sempre que o cookie de servidor expirar na configuração do aplicativo.This functionality is only necessary if you have selected Require users to log on again whenever the server cookie expires in your application configuration. Para obter mais informações, consulte Como configurar serviços de aplicativo cliente.For more information, see How to: Configure Client Application Services.