Asp.net

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

  • April 12, 2011

好的,所以我們目前正在使用 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 中右鍵點擊並以管理員身份執行:)

引用自:https://stackoverflow.com/questions/5629209