繁体   English   中英

从 .net 标准库读取 appsettings.json

[英]Reading appsettings.json from .net standard library

我已经使用 .NET 核心框架开始了一个新的 RESTful 项目。

我将我的解决方案分为两部分:框架(一组 .NET 标准库)和 Web(RESTful 项目)。

使用 Framework 文件夹,我为进一步的 web 项目提供了一些库,并且我想在其中一个项目中提供一个 Configuration class 和通用方法T GetAppSetting<T>(string Key)

我的问题是:如何才能访问 .NET Standard 中的 AppSettings.json 文件?

我找到了很多关于读取此文件的示例,但所有这些示例都将文件读取到 web 项目中,但没有人将其读取到外部库中。 我需要它为其他项目提供可重用的代码。

正如评论中已经提到的,你真的不应该这样做。 使用依赖注入来注入已配置的IOptions<MyOptions>

但是,您仍然可以将json文件作为配置加载:

IConfiguration configuration = new ConfigurationBuilder()
    .SetBasePath(Directory.GetCurrentDirectory()) // Directory where the json files are located
    .AddJsonFile("appsettings.json", optional: false, reloadOnChange: true)
    .Build();

// Use configuration as in every web project
var myOptions = configuration.GetSection("MyOptions").Get<MyOptions>();

请确保引用Microsoft.Extensions.ConfigurationMicrosoft.Extensions.Configuration.Json包。 有关更多配置选项, 请参阅文档

我扩展了这个场景,以便管理(可选)用户机密(来自 package: Microsoft.Extensions.Configuration.UserSecrets ):

IConfiguration configuration = new ConfigurationBuilder()
    .SetBasePath(Directory.GetCurrentDirectory()) // Directory where the json files are located
    .AddJsonFile("appsettings.json", optional: false, reloadOnChange: true)
    .AddUserSecrets(Assembly.GetEntryAssembly(),optional:true);
    .Build();

添加 Json 文件和用户机密的顺序在这里很重要。 请参阅调用 AddJsonFile 和 AddUserSecrets

我完全同意这不是首选方式(而是使用IOptions<>Dependency Injection并让应用程序配置库)。 但我之所以提到这一点,是因为我正在研究一个(非常古老的)库,该库正在从app.config (xml)中读取。 无法从应用程序配置此库,而是库直接执行此操作(期望 app.config 中的值)。 该库现在用于 Full Framework、.NET Core 和 .NET5(或更新版本)应用程序。 所以我也必须支持appsettings.json 实际上不可能以某种方式调整库,以便应用程序可以向库提供必要的配置值。 因此,我向它添加了对 JSON 的支持(暂时 - 也许以后我们可以花更多的精力让它可以从应用程序配置)

最后,我还支持环境,我的代码如下所示:

var builder = new ConfigurationBuilder()
                      .SetBasePath(Directory.GetCurrentDirectory())
                      .AddJsonFile("appsettings.json", optional: true, reloadOnChange: false);
            
var environment = Environment.GetEnvironmentVariable("ASPNETCORE_ENVIRONMENT");
if (!string.IsNullOrEmpty(environment))
{
    builder = builder.AddJsonFile(string.Format("appsettings.{0}.json", environment), optional: true, reloadOnChange: false);
    if (string.Equals(environment, "Development", StringComparison.CurrentCultureIgnoreCase))
    {
        builder = builder.AddUserSecrets(Assembly.GetEntryAssembly(),optional:true);
    }
}

请注意,我决定仅为开发scope 管理用户机密

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM