【问题标题】:appsettings.json and Class libraries that use ConfigurationManager.AppSettingsappsettings.json 和使用 ConfigurationManager.AppSettings 的类库
【发布时间】:2019-06-21 19:19:29
【问题描述】:

我正在将现有的 ASP.NET MVC 应用程序迁移到 ASP.NET Core。该解决方案有几个类库(提供数据访问、服务等)。其中许多类库使用静态ConfigurationManager.AppSettings["..."] 方式从 web.config 文件中获取配置。

但是,对于 ASP.NET Core 应用程序,没有 web.config 文件,并且看起来 ConfigurationManager 无法读取 appsettings.json。

我非常喜欢 ASP.NET Core 中的新配置系统,并且正在 Web 应用程序中使用它。

但是有没有一种“简单”的方法来迁移这些类库,而不必重写它们以使用新的配置系统?将读取 appsettings.json 的静态 ConfigurationManager.AppSettings["..."] 调用的任何基本替代品? (注意:我们最终会重写它们,但我们宁愿一次只做一个)

【问题讨论】:

    标签: asp.net-core configuration configurationmanager


    【解决方案1】:

    免责声明:我没有尝试使用类库,但这在 LinqPad 中有效:

    void Main()
    {
        var config = new Microsoft.Extensions.Configuration.ConfigurationBuilder()
            .AddInMemoryCollection(new Dictionary<string, string>
            {
                ["test"] = "test",
                ["test2:test"] = "test2"
            })
            .Build();
    
        foreach (var pair in config.AsEnumerable())
        {
            // Skips the (test2 = null) pair
            if (pair.Value != null)
            {
                ConfigurationManager.AppSettings.Set(pair.Key, pair.Value);
            }
        }
    
        ConfigurationManager.AppSettings["test"].Dump();
        ConfigurationManager.AppSettings["test2:test"].Dump();
    }
    

    您可以在初始化代码中加入类似的内容。 它设置 System.Configuration 应用设置集合可用的所有值。

    【讨论】:

      【解决方案2】:

      如果您使用的是 .NET Standard 2.0,则可以添加对 System.Configuration.ConfigurationManager NuGet 包的引用以访问 appSettings。

      您可以将app.Config 文件(不是web.Config)添加到您的 ASP.NET Core 项目以存储 appSettings。这将被复制到输出文件夹并在项目构建期间重命名为AppName.dll.config

      【讨论】:

      • 只是为了确认一下,你是说我需要做这两件事,对吧?仅仅使用 NuGet 包似乎并没有读取 appsettings.json 文件。
      • 是的,你需要两者都做。 NuGet 包读取 XML 应用程序配置文件(项目中的 app.Config,构建后的 appName.dll.config)。它不使用 appsettings.json。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2022-01-23
      • 2011-10-27
      • 2019-12-07
      • 2021-11-12
      • 1970-01-01
      • 2021-10-09
      • 1970-01-01
      相关资源
      最近更新 更多