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

Man*_*ngh 48 .net c# web-config .net-2.0

我在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>
Run Code Online (Sandbox Code Playgroud)

我的新部分secureAppSettings已解密,其中有两个键.

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

string userName = System.Configuration.ConfigurationManager.secureAppSettings["userName"];
string userPassword = System.Configuration.ConfigurationManager.secureAppSettings["userPassword"];
Run Code Online (Sandbox Code Playgroud)

但它正在回归secureAppSettings这些领域.

我怎样才能获得价值?

Dar*_*rov 61

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

NameValueCollection section = (NameValueCollection)ConfigurationManager.GetSection("secureAppSettings");
string userName = section["userName"];
string userPassword = section["userPassword"];
Run Code Online (Sandbox Code Playgroud)

  • 它是与 appsettings 不同的部分,这是名为“secureAppSettings”的新部分,我如何获取 appsettings 中的值,并且“secureAppSettings”现在已加密。 (2认同)
  • @Manu,对不起,我完全误解了你的问题,你是对的.我已经用正确的方式更新了我的答案. (2认同)
  • @ user1177636,是的,它是readonly.在Web应用程序中,修改web.config是不好的做法,因为这会导致应用程序重新启动.为此目的使用数据库或其他持久存储. (2认同)