asp.net - 如何在 Web 上下文中替换 OpenExeConfiguration (asp.net mvc 1)

标签 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);

它要么打开错误的配置文件(机器配置或 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/

相关文章:

.net - 我可以从 HttpModule 实例中放弃 InProc ASP.NET session 吗

javascript - 在 asp.net 上的文本框中格式化字符串

c# - 在 .NET 4.5 + 中使用 HttpClient 执行 XML 请求

jquery - 使用 JQuery .ajax,使用 jquery 'json' 与 'text' 时不会调用 Success 方法

c# - 如何在 Web 应用程序中获取用户的互联网连接速度?

c# - ASP MVC 如何将参数从 View 传递到 Controller C# 中的方法

c# - System.Drawing.Image 流式传输 C#

c# - Controller 参数 MVC ASP.NET

c# - 带枚举的 MVC3 RadioButtonFor

asp.net - C# ControlCollection 扩展 GetAllTextboxes