2011-06-13 55 views
41

我在web.config文件中得到了下面的示例代碼。如何從web.config中的自定義節中讀取值

<configuration> 
     <configSections> 
     <section name="secureAppSettings" type="System.Configuration.NameValueSectionHandler, System, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" /> 
     </configSections> 
<secureAppSettings> 
     <add key="userName" value="username"/> 
     <add key="userPassword" value="password"/> 
    </secureAppSettings> 
    </configuration> 

我的新節secureAppSettings被解密,並且裏面有兩個密鑰。

現在在我的代碼,我想訪問這些關鍵的東西象下面這樣:

string userName = System.Configuration.ConfigurationManager.secureAppSettings["userName"]; 
string userPassword = System.Configuration.ConfigurationManager.secureAppSettings["userPassword"]; 

但它返回null這些字段。

如何獲取值?

+0

最有用和一直在努力解決這是一個在我看來: http://stackoverflow.com/a/28600293/4250041 – benraay 2017-03-07 13:32:07

回答

51

你可以訪問它們的鍵/值對:

NameValueCollection section = (NameValueCollection)ConfigurationManager.GetSection("secureAppSettings"); 
string userName = section["userName"]; 
string userPassword = section["userPassword"]; 
+0

這是與appsettings相比,這是新的部分,名爲「secureAppSettings」,我如何獲得appsettings中的值,並且「secureAppSettings」現在被加密。 – 2011-06-13 10:18:44

+1

@Manu,對不起,我完全誤讀了你的問題,你說得對。我用正確的方式讀取了這些值,從而更新了我的答案。 – 2011-06-13 10:22:06

+0

@Manu,哦,夥計,好的:用'NameValueCollection'替換'var'。 – 2011-06-13 10:28:51

相關問題