twa*_*wal 272 c# asp.net-mvc
我试图从Web.config
与web层不同的层中读取文件中的键(相同的解决方案)
这是我正在尝试的:
string userName = System.Configuration.ConfigurationManager.AppSettings["PFUserName"];
string password = System.Configuration.ConfigurationManager.AppSettings["PFPassWord"];
Run Code Online (Sandbox Code Playgroud)
这是我appSettings
在Web.config
文件中:
<configuration>
....
<appSettings>
<add key="PFUserName" value="myusername"/>
<add key="PFPassWord" value="mypassword"/>
</appSettings>
....
</configuration>
Run Code Online (Sandbox Code Playgroud)
当我调试的代码username
和password
只是null
,所以它是没有得到键的值.
读这些值我做错了什么?
Hec*_*rea 462
请尝试使用WebConfigurationManager类.例如:
string userName = WebConfigurationManager.AppSettings["PFUserName"]
Run Code Online (Sandbox Code Playgroud)
yog*_*gee 39
var url = ConfigurationManager.AppSettings["ServiceProviderUrl"];
Run Code Online (Sandbox Code Playgroud)
我发现这个解决方案非常有用.它使用C#4.0 DynamicObject来包装ConfigurationManager.所以不要像这样访问值:
WebConfigurationManager.AppSettings["PFUserName"]
Run Code Online (Sandbox Code Playgroud)
您将它们作为属性访问:
dynamic appSettings = new AppSettingsWrapper();
Console.WriteLine(appSettings.PFUserName);
Run Code Online (Sandbox Code Playgroud)
编辑:添加代码片段以防万一链接变得陈旧:
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;
}
}
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
434158 次 |
最近记录: |