从 .net 标准库中读取 appsettings.json [英] Reading appsettings.json from .net standard library

查看:56
本文介绍了从 .net 标准库中读取 appsettings.json的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用 .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(string Key).

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?

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

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; 改用依赖注入.

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.ConfigurationMicrosoft.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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆