2008-11-05 81 views
3

我想通過web.config文件中的授權部分來使用基於角色的安全性。爲會員角色授權編輯Web.config

使用成員資格,我的應用程序將允許創建新的角色,因此,他們可以訪問的頁面需要動態設置。

我可以編程方式改變web.config中的這個部分來管理它嗎?如果是這樣,怎麼樣?

回答

5
using System.Configuration; 
using System.Web.Configuration; 

Configuration config = WebConfigurationManager.OpenWebConfiguration(Request.ApplicationPath); 
AuthorizationSection section = (AuthorizationSection)config.GetSection("system.web/authorization"); 

AuthorizationRule rule = new AuthorizationRule(AuthorizationRuleAction.Allow); 
rule.Roles.Add("admins"); 
section.Rules.Add(rule); 

config.Save(); 
Imports System.Configuration 
Imports System.Web.Configuration 

Dim config As Configuration = WebConfigurationManager.OpenWebConfiguration(Request.ApplicationPath) 
Dim section As AuthorizationSection = CType(config.GetSection("system.web/authorization"), AuthorizationSection) 

Dim rule As New AuthorizationRule(AuthorizationRuleAction.Allow) 
rule.Roles.Add("admins") 
section.Rules.Add(rule) 

config.Save() 

ASP.NET需要web.config中寫權限這項工作,所以要小心。