2016-07-15 63 views
4

編輯#2:config.FilePath顯示它正在查看與我期望的文件不同的文件:「C:\ Windows \ Microsoft.NET \ Framework64 \ v4.0.30319 \ CONFIG \ web.config文件」。我期待它在我的項目中使用web.config。需要弄清楚爲什麼會發生這種情況。從web.config中讀取AuthorizationSection提供的值不正確

我在我的web API中有一個方法,我試圖從我的web.config中的授權部分讀取值。根據我已經找到了,這應該工作:

public AuthorizationSetting GetAuthorizationSettings() 
    { 
     var config = WebConfigurationManager.OpenWebConfiguration(null); 
     var section = config.GetSection("system.web/authorization") as AuthorizationSection; 

     foreach (AuthorizationRule rule in section.Rules) 
     { 
      if (rule.Action.ToString().ToLower() == "allow") 
      { 
       Debug.WriteLine(rule); 
      } 
     } 

     return new AuthorizationSetting(); 
    } 

而且這是在web.config中包含授權信息的部分:

<system.web> 
    <compilation debug="true" targetFramework="4.5" /> 
    <httpRuntime targetFramework="4.5" /> 
    <identity impersonate="true" /> 
    <authentication mode="Windows" /> 
    <authorization> 
     <allow roles="role1,role2,role3"/> 
     <deny users="*"/> 
    </authorization> 
    </system.web> 

你可以看到,有一個允許一個人否認。當我運行代碼時,似乎只有一條規則。不應該有兩個,因爲有一個允許和否定?這條規則看起來有一個允許用戶的操作和「*」。這不是web.config中的內容。我在這裏錯過了什麼?

enter image description here

**編輯** 我認爲,它的讀取不同的web.config文件的可能性。但解決方案中只有一個其他web.config文件(在Views下)。我也改變它有相同的授權部分,但我仍然得到相同的結果。

回答

1

正如你已經想通了,在

%SystemRoot%\Microsoft.NET\Framework64\v4.0.30319\Config\ 

使用在OpenWebConfiguration負載服務器根web.config的path參數Null的文件說:

The virtual path to the configuration file. If null, the root Web.config file is opened.

但可以假設這將是該網站的根網頁配置,而不是服務器。無論如何,嘗試使用:

var config = WebConfigurationManager.OpenWebConfiguration("~"); 
+0

這樣做。不是很直觀。謝謝。 –