我正在尝试从与网络层不同的层中的Web.config
文件中读取密钥(相同解决方案)
以下是我的尝试:
string userName = System.Configuration.ConfigurationManager.AppSettings["PFUserName"];
string password = System.Configuration.ConfigurationManager.AppSettings["PFPassWord"];
这是appSettings
文件中的Web.config
:
<configuration>
....
<appSettings>
<add key="PFUserName" value="myusername"/>
<add key="PFPassWord" value="mypassword"/>
</appSettings>
....
</configuration>
当我调试代码username
而password
只是null
时,它就没有得到密钥的值。
读取这些值我做错了什么?
答案 0 :(得分:440)
尝试使用WebConfigurationManager类。例如:
string userName = WebConfigurationManager.AppSettings["PFUserName"]
答案 1 :(得分:34)
var url = ConfigurationManager.AppSettings["ServiceProviderUrl"];
答案 2 :(得分:6)
I found this solution to be quite helpful。它使用C#4.0 DynamicObject来包装ConfigurationManager。因此,而不是访问这样的值:
WebConfigurationManager.AppSettings["PFUserName"]
您将其作为财产访问:
dynamic appSettings = new AppSettingsWrapper();
Console.WriteLine(appSettings.PFUserName);
编辑:在案例链接变为陈旧时添加代码段:
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;
}
}
答案 3 :(得分:6)
如果调用者是另一个项目,则应该在调用者项目中编写配置而不是被调用者。
答案 4 :(得分:2)
完整路径是
System.Configuration.ConfigurationManager.AppSettings["KeyName"]
答案 5 :(得分:2)
将有两个Web.config文件。我想您可能对这两个文件感到困惑。
查看此图片:
在此图像中,您可以看到两个Web.config文件。您应该将常量添加到项目文件夹中而不是视图文件夹中的常量
希望这可能对您有帮助
答案 6 :(得分:1)
如果此项目正由另一个项目使用,则会出现此问题。确保将应用程序设置键复制到父项目的app.config或web.config。
答案 7 :(得分:1)
此外,您可以尝试使用此行从app.config
文件中获取字符串值。
var strName= ConfigurationManager.AppSettings["stringName"];
答案 8 :(得分:0)
,并在.config文件中进行以下设置:
<configuration>
<appSettings>
<add key="PFUserName" value="myusername"/>
<add key="PFPassWord" value="mypassword"/>
</appSettings>
</configuration>
尝试一下:
public class myController : Controller
{
NameValueCollection myKeys = ConfigurationManager.AppSettings;
public void MyMethod()
{
var myUsername = myKeys["PFUserName"];
var myPassword = myKeys["PFPassWord"];
}
}
答案 9 :(得分:-5)
对不起,我没有对此进行过测试,但我认为它是这样做的:
var filemap = new System.Configuration.ExeConfigurationFileMap();
System.Configuration.Configuration config = System.Configuration.ConfigurationManager.OpenMappedExeConfiguration(filemap, System.Configuration.ConfigurationUserLevel.None);
//usage: config.AppSettings["xxx"]