从.net标准库中读取appsettings.json

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

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

使用Framework文件夹,我提供了一些用于进一步增强web项目的库,并且我想提供一个带有通用方法T GetAppSetting(string Key)的Configuration类。

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

我已经找到了很多关于阅读这个文件的例子,但所有这些例子都将文件读入了web项目,没有人将这个文件读入一个extarnal库。 我需要它为Others项目提供可重用的代码。

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

但是,您仍然可以将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(); 

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