.NET Core 使用 ConfigurationManager.AppSettings 使用标准 .NET 库

标签 .net asp.net-core

我有一个使用多年的标准 .NET 4.5.2 库。它依赖于 ConfigurationManager.AppSettings,这意味着我必须确保在我的应用程序或 web.config 文件的 appSettings 部分中有一组特定的设置。无法传递这些值。您必须将它们放入 appSettings 部分。

我正在 .NET Core 中开始一个新项目,但目标是 Net452,以便我可以利用许多库(到目前为止工作正常)。

我遇到了这个最新库的问题,因为我不知道如何正确设置设置以便 ConfigurationManager.AppSettings 找到它们。

将它们放在 appSettings.json 中似乎不起作用。将它们放在 web.config 中似乎也不起作用。

这甚至可能吗?

谢谢!

最佳答案

是的,您可能想要什么,但是您应该手动进行(我不知道是否有简单的方法)。

假设您在 appsettings.json 中有一些设置像下面这样:

{
    "AppSettings" : {
        "Setting1": "Setting1 Value"
     }
}

Startup.cs构造函数集ConfigurationManager.AppSettings具有值(value):
    public Startup(IHostingEnvironment env)
    {
        var builder = new ConfigurationBuilder()
            .SetBasePath(env.ContentRootPath)
            .AddJsonFile("appsettings.json", optional: true, reloadOnChange: true)
            .AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true)
            .AddEnvironmentVariables();
        Configuration = builder.Build();

        // copy appsetting data into ConfigurationManager.AppSettings
        var appSettings = Configuration.GetSection("AppSettings").GetChildren();
        foreach (var setting in appSettings.AsEnumerable())
        {
            ConfigurationManager.AppSettings[setting.Key] = setting.Value;
        }
    }

并在类库中获取值:
var conStr =  ConfigurationManager.AppSettings["Setting1"].ToString();

关于.NET Core 使用 ConfigurationManager.AppSettings 使用标准 .NET 库,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39520029/

相关文章:

c# - 在 Linux 上编写 C# 程序时缺少类型 'Uri'

c# - 使用 DI 访问 Startup.cs 中的 NPGSQL

asp.net-core - 如何在asp .net core 3.1中设置请求超时

.net - netstandard1.0/netstandard1.2 和 LINQ

.net - 如何在EF多对多关系中添加新记录?

c# - 如何获取数组中最大数字的索引?

c# - 如何以这种方式调整 WPF 网格面板的大小?

.net - VB.NET 内存管理

asp.net-core - Kestrel 失败 : Can not load Microsoft. Extensions.Logging.Abstractions

c# - 无法解析 JSON 文件,Progam.cs asp.net core 中出错