Asp.net2.0中基於Forms驗證的角色驗證授權(2)
阿新 • • 發佈:2019-01-04
以admin角色為例,只允許角色為admin的使用者訪問
1.設定Web.Config檔案
<roleManager enabled="true"/>
<authorization>
<allow roles="admin"/>
<deny users="*"/>
</authorization>
2.在Global.asax檔案的Application_Start事件處理方法中新增角色
if(!Roles.RoleExists("admin")) Roles.CreateRole("admin");
3.登入時對Admin 角色的使用者新增如下程式碼:
FormsAuthentication.SetAuthCookie (tb_username.Text, false);
if(!Roles.IsUserInRole (tb_username.Text,"admin"))
Roles.AddUserToRole (tb_username.Text, "admin");
Response.Redirect (FormsAuthentication.GetRedirectUrl (tb_username.Text, false));
4.前提:1)有角色admin存在;2)當前使用者屬於admin角色