从使用IIS部署的webapplicaion使用的库中读取web.config

Sta*_*ful 7 .net c# asp.net iis asp.net-web-api

我在IIS上部署了一个Web应用程序.此Web应用程序正在使用想要访问Web.config的库.

示例:Foo.dll是部署在IIS上的Web应用程序.Foo.dll使用了Utility.dll

Foo.Utility namepsace中有一段代码,它想从Foo应用程序访问web.config并读取配置值

Configuration config = WebConfigurationManager.OpenWebConfiguration(null);
string cacheDir = config.AppSettings.Settings["abc"].Value;
Run Code Online (Sandbox Code Playgroud)

目前config.FilePath = C:\ Windows\Microsoft.NET\Framework64\v4.0.30319\Config\web.config

将我的代码更改为:

Configuration config = WebConfigurationManager.OpenWebConfiguration(Assembly.GetCallingAssembly().Location);
string cacheDir = config.AppSettings.Settings["abc"].Value;
Run Code Online (Sandbox Code Playgroud)

现在我的Assembly.GetCallingAssembly().位置是:C:\ Windows\Microsoft.NET\Framework64\v4.0.30319\Temporary ASP.NET Files\root\62f5c902\849205ff\assembly\dl3\c28d4647\10e128d3_7449d001\foo.dll

有人可以帮我理解如何从使用IIS部署应用程序的地方读取web.config吗?

如需更多信息或问题不明确,请在下方发表评论.会更新它

Aug*_*eto 5

您必须使用 System.Configuration 中的 ConfigurationManager。首先,您必须添加对 System.Configuration.dll 程序集的引用,然后像这样使用它:

using System.Configuration;
...
string valueOfAbc = ConfigurationManager.AppSettings["abc"];
Run Code Online (Sandbox Code Playgroud)

ConfigurationManager 将从应用程序的主机读取配置文件。在你的情况下,web.config 文件。

参考:

  1. 配置管理器类
  2. 应用程序配置文件

  • 您应该注意,这需要对“System.Configuration.dll”程序集的引用,默认情况下不会引用该程序集。 (2认同)