【问题标题】:Read config file from asp.net从 asp.net 读取配置文件
【发布时间】:2012-12-23 12:19:48
【问题描述】:

我正在创建一个 Web 应用程序,它调用一个 DLL 来运行单元测试,我还有另一个 DLL(DataAccessLayer),它执行连接并执行对引用主 DLL 的 SQL 的查询。两个 DLL 使用相同的配置文件来读取设置。

从 VS 运行应用程序时,应用程序运行良好。但是,当 Web 应用程序部署到 IIS 时,DLL 似乎无法从配置文件中读取设置。

经过一番研究,我发现我可能必须在 web.config 文件中明确定义配置元素,但是我不知道如何实现。有人可以指出我正确的方向吗?

我实际上是使用 ConfigurationManager 和以下代码检索设置:-

   public string GetValue(string key)
   {
       var appConfig = ConfigurationManager.OpenExeConfiguration("path to dll");
       strKeyValue = appConfig.AppSettings.Settings[key].Value;



       return strKeyValue;
   }

谢谢。

【问题讨论】:

标签: c# asp.net .net config configurationmanager


【解决方案1】:

使用WebConfigurationManager.AppSettings["HelloWorldKey"]; 从 web.config 读取 AppSettings。

【讨论】:

  • 设置不在 web.config 中,它们在一个单独的 App.config 中,由我正在调用的 dll 使用。
  • 然后将它们移动到 web.config - .NET 将使用 web.config 中的设置覆盖 dll 设置。使用 app.config 作为默认设置,并使用 dll 中的 propterties.settings 访问它们。顺便说一句:大多数时候不需要配置 dll - 只需在调用中将配置作为参数传递即可。
【解决方案2】:

只需在部署应用程序之前直接在 web.config 中设置您提到的 DLL 使用的所有 appSettings 值。您不需要在运行时修改它(无论如何也不应该,因为对 web.config 的任何修改都会导致应用程序重新启动)

【讨论】:

  • 所以我将我的配置文件的所有 appSettings 放在 web.config 中,然后在我的 dll 中我使用 WebConfigurationManager 从 web.config 中检索值?
  • DLL 将自动从 Web.config 读取值。您应该在所有项目上使用 ConfigurationManager.AppSettings。我相信 WebConfigurationManager 已被弃用。
  • @Krafo,使用System.Configuration.ConfigurationManager.AppSettings[key]。并且您必须在您的 dll 中显式添加对 System.Configuration 的引用(默认情况下它通常不包含在 Visual Studio 的 dll 项目中)。
  • 这正是我希望它的行为方式,但事实并非如此。 Web.config 不会覆盖 machine.config 文件的 appSettings 值。
【解决方案3】:

将 app.config 中使用的 connectionstringAppSettingApplicationSettings 添加到 web.config 中,我知道这是一项手动任务,但这是配置读取设置的唯一方法。

【讨论】:

    【解决方案4】:

    使用以下代码访问连接字符串

    string filePath= WebConfigurationManager.AppSettings["Pathfile"].ToString();
    

    网络配置文件

    <configuration>
           ....
         <appSettings>
           <add key="Pathfile" value="Path to dll"/>
         </appSettings>
        ....
    </configuration>
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-12-24
      • 1970-01-01
      • 2012-06-18
      • 2011-09-24
      • 2017-09-22
      相关资源
      最近更新 更多