Reading a key from the Web.Config using ConfigurationManager

后端 未结 10 1790
情书的邮戳
情书的邮戳 2020-11-28 17:55

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:

         


        
相关标签:
10条回答
  • 2020-11-28 18:18

    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;
        }
    }
    
    0 讨论(0)
  • 2020-11-28 18:19

    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"];
        }
    }
    
    0 讨论(0)
  • 2020-11-28 18:26

    Try using the WebConfigurationManager class instead. For example:

    string userName = WebConfigurationManager.AppSettings["PFUserName"]
    
    0 讨论(0)
  • 2020-11-28 18:26

    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.

    0 讨论(0)
提交回复
热议问题