2008-11-05 90 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中写权限这项工作,所以要小心。