Web.config editing for Membership Role Authorizati

2019-05-12 15:44发布

问题:

I want to user Role based security through the authorization section in the web.config file.

Using Membership, my application will allow for new Roles to be created, and thus, the pages they can access need to be set dynamically.

Can I programatically alter this section in the web.config to manage this? If so, how?

回答1:

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 needs web.config write permission for this to work, so be careful.