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条回答
forever°为你锁心
2楼-- · 2020-01-24 19:26

Try using the WebConfigurationManager class instead. For example:

string userName = WebConfigurationManager.AppSettings["PFUserName"]
查看更多
可以哭但决不认输i
3楼-- · 2020-01-24 19:29

I found this solution to be quite helpful. It uses C# 4.0 DynamicObject to wrap the ConfigurationManager. So instead of accessing values like this:

 WebConfigurationManager.AppSettings["PFUserName"]

you access them as a property:

dynamic appSettings = new AppSettingsWrapper();
Console.WriteLine(appSettings.PFUserName);  

EDIT: Adding code snippet in case link becomes stale:

public class AppSettingsWrapper : DynamicObject
{
     private NameValueCollection _items;

    public AppSettingsWrapper()
    {
        _items = ConfigurationManager.AppSettings;
    }

     public override bool TryGetMember(GetMemberBinder binder, out object result)
    {
        result = _items[binder.Name];
        return result != null;
    }
}
查看更多
地球回转人心会变
4楼-- · 2020-01-24 19:30

This issue happens if this project is being used by another project. Make sure you copy the app setting keys to the parent project's app.config or web.config.

查看更多
【Aperson】
5楼-- · 2020-01-24 19:30

with assuming below setting in .config file:

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

try this:

public class myController : Controller
{
    NameValueCollection myKeys = ConfigurationManager.AppSettings;

    public void MyMethod()
    {
        var myUsername = myKeys["PFUserName"];
        var myPassword = myKeys["PFPassWord"];
    }
}
查看更多
登录 后发表回答