从.net标准库读取appsettings.json [英] Reading appsettings.json from .net standard library
问题描述
我已经使用.NET Core Framework开始了一个新的RESTful项目。
i have started a new RESTful project using .NET Core Framework.
我将解决方案分为两部分:框架(.NET标准库集)和Web (RESTful项目)。
I divided my solution in two parts: Framework (set of .NET standard libraries) and Web (RESTful project).
借助Framework文件夹,我为进一步的Web项目提供了一些库,在其中一个库中,我想为Configuration类提供通用方法 T GetAppSetting< T>(字符串键)
。
With Framework folder i provide some of library for furthers web project and into one of these i'd like to provide a Configuration class with the generic method T GetAppSetting<T>(string Key)
.
我的问题是:如何我可以访问.NET Standard中的AppSettings.json文件吗?
My question is: how can i get the access to the AppSettings.json file in .NET Standard?
我找到了很多有关读取此文件的示例,但是所有这些示例都将文件读入了该网络项目,没有人将其放入外部图书馆。我需要它具有其他项目的可重用代码。
I have found so many example about reading this file, but all these examples read the file into the web project and no-one do this into an extarnal library. I need it to have reusable code for Others project.
推荐答案
正如评论中已经提到的那样,您真的不应该这样做。 注入已配置的 IOptions< MyOptions>
而是使用依赖项注入。
As already mentioned in the comments, you really shouldn't do it. Inject a configured IOptions<MyOptions>
using dependency injection instead.
但是,您仍然可以加载json文件作为配置:
However, you can still load a json file as configuration:
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
软件包。有关更多配置选项,请请参阅文档。
Make sure to reference the Microsoft.Extensions.Configuration
and Microsoft.Extensions.Configuration.Json
packages. For more configuration options see the documentation.
这篇关于从.net标准库读取appsettings.json的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!