2011-06-13 58 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

相关问题