twal twal - 3 months ago 19
C# Question

Reading a key from the Web.Config using ConfigurationManager

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

Try using the WebConfigurationManager class instead. For example:

string userName = WebConfigurationManager.AppSettings["PFUserName"]
Comments