简体   繁体   English

如何创造 <location> web.config文件中的标签?

[英]How to create <location> tag in web.config file?

Is it possible to add location tag dynamically with c# in web config? 是否可以在Web配置中使用c#动态添加位置标记?

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. 文件夹b是在运行时创建的,我想添加对创建它的用户的访问权限。 The number of the folders created is unknown. 创建的文件夹数量未知。

I use forms authentication. 我使用表单身份验证。

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. 就像@SouthShoreAK一样,我不认为可以这样做,但总是有选项,一种方法可以是通过一个基础web.config,你可以编辑你创建的每个文件夹中的保存添加您需要的授权,我在下面的代码执行此操作。

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 你的WebEmpty.config就是这样的

<?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. 希望这有帮助。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM