Lol*_*llo 5 c# .net-core asp.net-core-webapi asp.net-core-2.0 .net-standard-2.0
我已经使用.NET Core Framework启动了一个新的RESTful项目。
我将解决方案分为两部分:框架(.NET标准库集)和Web(RESTful项目)。
对于Framework文件夹,我提供了一些用于进一步开发Web项目的库,在其中一个库中,我想为Configuration类提供通用方法T GetAppSetting<T>(string Key)。
我的问题是:如何获得对.NET Standard中AppSettings.json文件的访问?
我发现了很多有关读取此文件的示例,但是所有这些示例都将文件读取到Web项目中,没有人将其读取到外部库中。我需要它具有“其他”项目的可重用代码。
Bru*_*ell 11
正如评论中已经提到的那样,您真的不应该这样做。而是使用依赖项注入注入配置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>();
Run Code Online (Sandbox Code Playgroud)
确保引用Microsoft.Extensions.Configuration和Microsoft.Extensions.Configuration.Json软件包。有关更多配置选项,请参阅文档。
| 归档时间: |
|
| 查看次数: |
5461 次 |
| 最近记录: |