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:
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;
}
}
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"];
}
}
Try using the WebConfigurationManager class instead. For example:
string userName = WebConfigurationManager.AppSettings["PFUserName"]
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.