Reading a key from the Web.Config using Configurat

2020-01-24 18:39发布

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?

10条回答
孤傲高冷的网名
2楼-- · 2020-01-24 19:06

Full Path for it is

System.Configuration.ConfigurationManager.AppSettings["KeyName"]
查看更多
Fickle 薄情
3楼-- · 2020-01-24 19:08

There will be two Web.config files. I think you may have confused with those two files.

Check this image:

click this link and check this image

In this image you can see two Web.config files. You should add your constants to the one which is in the project folder not in the views folder

Hope this may help you

查看更多
虎瘦雄心在
4楼-- · 2020-01-24 19:17

If the caller is another project, you should write the config in caller project not the called one.

查看更多
够拽才男人
5楼-- · 2020-01-24 19:23
  var url = ConfigurationManager.AppSettings["ServiceProviderUrl"];
查看更多
Summer. ? 凉城
6楼-- · 2020-01-24 19:23

Also you can try this line to get string value from app.config file.

var strName= ConfigurationManager.AppSettings["stringName"];
查看更多
混吃等死
7楼-- · 2020-01-24 19:23

Sorry I've not tested this but I think it's done like this:

var filemap = new System.Configuration.ExeConfigurationFileMap();            
System.Configuration.Configuration config =  System.Configuration.ConfigurationManager.OpenMappedExeConfiguration(filemap, System.Configuration.ConfigurationUserLevel.None);

//usage: config.AppSettings["xxx"]
查看更多
登录 后发表回答