c# - 从 .net 标准库中读取 appsettings.json
问题描述
我已经使用 .NET Core Framework 开始了一个新的 RESTful 项目。
我将我的解决方案分为两部分:框架(一组 .NET 标准库)和 Web(RESTful 项目)。
使用 Framework 文件夹,我为进一步的 Web 项目提供了一些库,并且在其中之一中,我想提供一个具有通用方法的 Configuration 类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.Configuration
和Microsoft.Extensions.Configuration.Json
包。有关更多配置选项,请参阅文档。
推荐阅读
- node.js - 如何通过有限的api调用将mongodb连接到shopify?
- reactjs - React 的 useEffect 中更高级的比较
- elasticsearch - 引导带检查失败 elasticsearch
- c - 如何使用 syslog-ng 只登录 **mylog**,而不是 **mylog** 和 **syslog**?
- java - ScriptResult 类型的方法 GetNewPage() 未定义
- python - Django:如果查询集注释中的任何值为空,如何返回无
- scala - 如何通过像 python pandas 这样的 spark 数据框中的列获取对?
- php - 从 Wordpress 本地上传插件时的权限问题
- karate - 如何获取将在场景中执行的所有细节
- python - 如果条件为假,如何返回变量名字符串?