首页 > 解决方案 > 从 .net 标准库中读取 appsettings.json

问题描述

我已经使用 .NET Core Framework 开始了一个新的 RESTful 项目。

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

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

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

我发现了很多关于读取这个文件的例子,但是所有这些例子都将文件读入了 web 项目,没有人将这个文件读入外部库。我需要它为其他项目提供可重用的代码。

标签: c#.net-coreasp.net-core-2.0asp.net-core-webapi.net-standard-2.0

解决方案


正如评论中已经提到的,你真的不应该这样做。而是使用依赖注入注入配置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包。有关更多配置选项,请参阅文档


推荐阅读