簡體   English   中英

如何創造 <location> web.config文件中的標簽?

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

是否可以在Web配置中使用c#動態添加位置標記?

例如,我想添加:

  <location path="a/b">
    <system.web>
      <authorization>
        <allow users="xxx"/>
        <deny users="*"/>
      </authorization>
    </system.web>
  </location>

文件夾b是在運行時創建的,我想添加對創建它的用戶的訪問權限。 創建的文件夾數量未知。

我使用表單身份驗證。

就像@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
}

你的WebEmpty.config就是這樣的

<?xml version="1.0"?>
<configuration>
</configuration>

你保存的文件看起來像這樣

<?xml version="1.0" encoding="utf-8"?>
<configuration>
    <system.web>
        <authorization>
            <allow users="userName" />
            <deny users="*" />
        </authorization>
    </system.web>
</configuration>

要考慮的另一件事是創建配置文件的讀/寫權限,但我認為由於動態文件夾創建,您已經擁有它。

希望這有幫助。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM