如何从web.config中的自定义部分读取值

时间:2022-11-06 20:21:06

I have got below sample code in web.config file.

我在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>

My new section secureAppSettings is decrypted and is having two keys inside it.

我的新部分secureAppSettings已被解密,其中有两个密钥。

Now in my code, I want to access these key something like below:

现在在我的代码中,我想访问以下这些键:

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

But it is returning null for these fields.

但它为这些字段返回null。

How can I get the values?

我怎样才能获得价值?

1 个解决方案

#1


52  

You could access them as key/value pairs:

您可以将它们作为键/值对进行访问:

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

#1


52  

You could access them as key/value pairs:

您可以将它们作为键/值对进行访问:

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