Reputation: 919
Is it possible to add location tag dynamically with c# in web config?
for example, I want to add:
<location path="a/b">
<system.web>
<authorization>
<allow users="xxx"/>
<deny users="*"/>
</authorization>
</system.web>
</location>
The folder b is created on run time, and I want to add an access to the user which created it. The number of the folders created is unknown.
I use forms authentication.
Upvotes: 3
Views: 3361
Reputation: 46
Like @SouthShoreAK I don't think that can be done in this way, but always there are options, one approach could be by having a base web.config that you can edit an save in each folder that you create in wich you add the authorization that you need, the code that I put below does this.
try
{
//Load the empty base configuration file
Configuration config = WebConfigurationManager.OpenWebConfiguration("~/WebEmpty.config");
//Get te authorization section
AuthorizationSection sec = config.GetSection("system.web/authorization") as AuthorizationSection;
//Create the access rules that you want to add
AuthorizationRule allowRule = new AuthorizationRule(AuthorizationRuleAction.Allow);
allowRule.Users.Add("userName");
//allowRule.Users.Add("userName2"); Here can be added as much users as needed
AuthorizationRule denyRule = new AuthorizationRule(AuthorizationRuleAction.Deny);
denyRule.Users.Add("*");
//Add the rules to the section
sec.Rules.Add(allowRule);
sec.Rules.Add(denyRule);
//Save the modified config file in the created folder
string path = MapPath("~/NewFolder/Web.config");
config.SaveAs(path);
}
catch (Exception ex)
{
//Handle the exceptions that could appear
}
Your WebEmpty.config would be like this
<?xml version="1.0"?>
<configuration>
</configuration>
And your saved file looks like this
<?xml version="1.0" encoding="utf-8"?>
<configuration>
<system.web>
<authorization>
<allow users="userName" />
<deny users="*" />
</authorization>
</system.web>
</configuration>
Another thing to consider would be the read/write permission to create the config file, but I think that you already have it because of the dynamic folder creation.
Hope this help.
Upvotes: 1