好的,所以我们目前正在使用 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);
它要么打开错误的配置文件(机器配置或 VS/IDE/Web.config)要么提示错误:
{System.Configuration.ConfigurationErrorsException:加载配置文件时出错:无法映射路径“/”。 ---> System.InvalidOperationException:无法映射路径“/”。
编辑 -
好的,这样的组合
config = System.Web.Configuration.WebConfigurationManager.OpenWebConfiguration("~");
并以管理员身份运行 Visual Studio 2008。希望我们在部署到 Web 服务器/客户端环境时不会遇到安全/权限问题!
最佳答案
所以最后我使用了这段代码(必须处理 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);
还必须在管理员模式下运行 Visual Studio - 我发现您可以将其设置为快捷方式上的属性,因此您无需记住每次在 Windows 7 中右键单击并以管理员身份运行:)
关于asp.net - 如何在 Web 上下文中替换 OpenExeConfiguration (asp.net mvc 1),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5629209/