Jen*_*Jen 20 asp.net asp.net-mvc c#-3.0
好的,所以我们当前正在使用OpenExeConfiguration来读取配置文件,但是在Web上下文中运行时这不起作用.
我尝试了各种不同的方式以编程方式打开web.config但我似乎无法让它读取正确的web.config文件.如果重要,我目前正在VS 2008中进行调试.
1. config = System.Web.Configuration.WebConfigurationManager.OpenWebConfiguration(System.Web.HttpContext.Current.Request.ApplicationPath);
2. config = ConfigurationManager.OpenMappedExeConfiguration(new ExeConfigurationFileMap { ExeConfigFilename = "web.config" }, ConfigurationUserLevel.None);
3. config = System.Web.Configuration.WebConfigurationManager.OpenWebConfiguration("~");
4. config = System.Web.Configuration.WebConfigurationManager.OpenWebConfiguration(null);
5. System.Web.Configuration.WebConfigurationManager.OpenWebConfiguration(System.Web.Hosting.HostingEnvironment.ApplicationVirtualPath);
Run Code Online (Sandbox Code Playgroud)
它要么打开错误的配置文件(机器配置,或VS /IDE/Web.config)或抱怨错误:
{System.Configuration.ConfigurationErrorsException:加载配置文件时出错:无法映射路径'/'.---> System.InvalidOperationException:无法映射路径'/'.
编辑 - 确定如此组合
config = System.Web.Configuration.WebConfigurationManager.OpenWebConfiguration("~");
Run Code Online (Sandbox Code Playgroud)
并运行Visual Studio 2008作为管理员工作.我们希望在部署到我们的Web服务器/客户端环境时不会遇到安全/权限问题!
Jen*_*Jen 29
所以最后我使用了这段代码(必须处理Web应用程序是否正在运行,或者我们的单元测试代码是否正在运行).
System.Configuration.Configuration config = null;
if (System.Web.HttpContext.Current != null && !System.Web.HttpContext.Current.Request.PhysicalPath.Equals(string.Empty))
config = System.Web.Configuration.WebConfigurationManager.OpenWebConfiguration("~");
else
config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
Run Code Online (Sandbox Code Playgroud)
还必须以管理员模式运行Visual Studio - 我发现您可以在快捷方式中设置为属性,因此您无需记住每次在Windows 7中右键单击并以管理员身份运行:)
| 归档时间: |
|
| 查看次数: |
8004 次 |
| 最近记录: |