Reading a key from the Web.Config using ConfigurationManager

twal picture twal · Jan 4, 2011 · Viewed 473.3k times · Source

I am trying to read the keys from the Web.config file in a different layer than the web layer (Same solution)

Here is what I am trying:

string userName = System.Configuration.ConfigurationManager.AppSettings["PFUserName"];
string password = System.Configuration.ConfigurationManager.AppSettings["PFPassWord"];

And here is my appSettings in the Web.config file:

<configuration>
   ....
   <appSettings>
      <add key="PFUserName" value="myusername"/>
      <add key="PFPassWord" value="mypassword"/>
   </appSettings>
   ....
</configuration>

When I debug the code username and password are just null, so it is not getting the value of the keys.

What am I doing wrong to read these values?

Answer

Hector Correa picture Hector Correa · Jan 4, 2011

Try using the WebConfigurationManager class instead. For example:

string userName = WebConfigurationManager.AppSettings["PFUserName"]