2010-06-11 48 views
13

的System.Web部分應該是簡單的,但無論我嘗試返回null:如何閱讀從web.config中

const string key = "system.web"; 

var sectionTry1 = WebConfigurationManager.GetSection(key); 

var sectionTry2 = ConfigurationManager.GetSection(key); 

我敢肯定,我已經這樣做過。

我正在使用MVC,如果這有所作爲。

回答

23

是一個白癡 - system.web不是配置部分,但配置組。如果我將密鑰更改爲實際部分,那麼這兩種方法都可以正常工作。下面是一個使用ConfigurationManager中:

const string outputCacheSettingsKey = "system.web/caching/outputCacheSettings";   

var outputCacheSettingsSection = ConfigurationManager.GetSection(outputCacheSettingsKey) as OutputCacheSettingsSection; 
+0

爲了記錄相同的作品,如果你需要獲得編譯部分,除了你將其轉換爲'CompilationSection' – 2013-10-03 16:02:02

5

我想訪問system.web與訪問appSettings略有不同。

試試這個:

string configPath = "/MyAppRoot"; 

Configuration config = WebConfigurationManager.OpenWebConfiguration(configPath); 

IdentitySection section = (IdentitySection)config.GetSection("system.web/identity"); 

你需要轉換你試圖訪問特定類型的System.Web的相關部分。

+0

首先,檢查是否'的System.Web/identity' ***部分存在***? – Kiquenet 2017-10-18 12:44:05

4

這爲我工作:

public Int32 GetmaxRequestLength() 
{ 
    // Set the maximum file size for uploads in bytes. 
    var section = ConfigurationManager.GetSection("system.web/httpRuntime") as HttpRuntimeSection; 
    // return length converted to kbytes or return default value as specified 
    return (Int32) Math.Round((decimal)(section != null ? (double)section.MaxRequestLength * 1024/1000 : 5.120), 2); 
} 
+0

'ConfigurationManager.GetSection'讀取*** machine.config ***或*** web.config ** *?只有我想閱讀*** web.config *** – Kiquenet 2017-10-18 13:05:07