ClientRolePrincipal.IsInRole(String) 方法
定义
重要
一些信息与预发行产品相关,相应产品在发行之前可能会进行重大修改。 对于此处提供的信息,Microsoft 不作任何明示或暗示的担保。
获取一个值,该值指示由 ClientRolePrincipal 表示的用户是否扮演指定的角色。
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
参数
- role
- String
要检查的角色。
返回
如果用户处于指定的角色,则为 true
;如果用户不处于指定的角色或者未通过身份验证,则为 false
。
实现
示例
以下示例代码演示如何仅在用户处于“经理”角色时使用此方法显示按钮。 此示例要求具有Button初始Visible属性值的名为 managerOnlyButton
。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
注解
通常,将调用 IsInRole 属性返回的 IPrincipal 的 方法 static
Thread.CurrentPrincipal 。 但是,可以将属性值ClientRolePrincipal强制转换为CurrentPrincipal引用以显式调用此方法,如示例部分所示。
如果用户登录名已过期,则 IsInRole 方法会始终返回 false
。 如果应用程序在身份验证后不久调用方法一次, IsInRole 则不会发生这种情况。 如果应用程序必须在其他时间检索用户角色,则可能要添加代码以重新验证登录名已过期的用户。 如果所有有效用户都分配给角色,则可以通过调用 ClientRoleProvider.GetRolesForUser 方法来确定登录名是否已过期。 如果不返回任何角色,则登录名已过期。 有关此功能的示例,请参阅 GetRolesForUser 方法。 仅当在应用程序配置中选择了“每次服务器 Cookie 到期时要求用户重新登录”时,此功能才是必需的。
适用于
另请参阅
反馈
https://aka.ms/ContentUserFeedback。
即将发布:在整个 2024 年,我们将逐步淘汰作为内容反馈机制的“GitHub 问题”,并将其取代为新的反馈系统。 有关详细信息,请参阅:提交和查看相关反馈