管理角色
下面的例子演示了认证用户如何使用角色管理器特性。所有的示例页面都拒绝匿名用户访问。在默认情况下,ASP.NET中是没有激活角色管理器特性的。但是,下面的例子中使用的web.config显式地激活了角色管理器特性。
添加和删除角色
下面的例子演示了如何使用Roles.CreateRole和Roles.DeleteRole方法建立和删除角色。在你建立角色或删除已有角色之后,页面使用Roles.GetAllRoles方法显示系统中的所有可用角色。Roles.GetAllRoles的返回值可以轻易地绑定到任何支持数据绑定的控件。你至少需要建立一个叫做"Administrators"的角色。
在你建立和删除角色的时候,请注意角色管理器特性不允许你建立重复的角色。同时还要注意,在默认情况下,角色管理器不允许你删除填充过的角色。
Sub btnCreateRole_Click(ByVal sender As Object, ByVal e As System.EventArgs) Dim roleName As String = txtCreateRole.Text
Try Roles.CreateRole(roleName) lblResults.Text = Nothing lblResults.Visible = False txtCreateRole.Text = Nothing Catch ex As Exception lblResults.Text = "Could not create the role: " + Server.HtmlEncode(ex.Message) lblResults.Visible = True End Try End Sub
Sub btnDeleteRole_Click(ByVal sender As Object, ByVal e As System.EventArgs) If (lbxAvailableRoles.SelectedIndex <> -1) Then Try Roles.DeleteRole(lbxAvailableRoles.SelectedValue)
lblResults.Text = Nothing lblResults.Visible = False Catch ex As Exception lblResults.Text = "Could not delete the role: " + Server.HtmlEncode(ex.Message) lblResults.Visible = True End Try End If End Sub |
向角色中添加用户和从角色中删除用户
下面的例子使用了前面例子中建立的角色,它演示了如何向角色添加用户和从角色中删除用户。使用Roles.AddUserToRole方法向角色中添加用户,使用Roles.RemoveUserFromRole方法从角色中删除用户。在给角色添加用户之前,先检查该用户是否已经是该角色的成员。这种检查是必要的,因为如果你试图给角色多次添加同一个用户,角色管理器会抛出异常。在前面的例子中,角色信息和角色的成员都显示在数据绑定控件中。用户所属的角色列表通过Roles.GetRolesForUser方法获取。要运行下面的例子,就要确保把你自己加入"Administrators"角色。
Sub btnAddUserToRole_Click(ByVal sender As Object, ByVal e As System.EventArgs) If (lbxAvailableRoles.SelectedIndex <> -1) Then Dim selectedRole As String = lbxAvailableRoles.SelectedValue
If Not Roles.IsUserInRole(selectedRole) Then Try Roles.AddUserToRole(User.Identity.Name, selectedRole) RefreshCurrentRolesListBox() Catch ex As Exception lblResults.Text = "Could not add the user to the role: " + Server.HtmlEncode(ex.Message) lblResults.Visible = True End Try Else lbxAvailableRoles.SelectedIndex = -1 End If End If End Sub
Sub btnDeleteUserFromRole_Click(ByVal sender As Object, ByVal e As System.EventArgs) Dim selectedRole As String = lbxUserRoles.SelectedValue
If (lbxUserRoles.SelectedIndex <> -1) Then Try Roles.RemoveUserFromRole(User.Identity.Name, selectedRole) 数据挖掘论坛 RefreshCurrentRolesListBox() Catch ex As Exception lblResults.Text = "Could not remove the user from the role: " + Server.HtmlEncode(ex.Message) lblResults.Visible = True End Try End If End Sub |
数据挖掘论坛