c# - 从 .net 标准库中读取 appsettings.json

标签 c# .net-core asp.net-core-2.0 asp.net-core-webapi .net-standard-2.0

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

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

通过 Framework 文件夹,我为进一步的 Web 项目提供了一些库,并且我想在其中之一中提供具有通用方法的配置类 T GetAppSetting<T>(string Key) .

我的问题是:如何获得对 .NET Standard 中 AppSettings.json 文件的访问权限?

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

最佳答案

正如评论中已经提到的,你真的不应该这样做。 Inject a configured IOptions<MyOptions> using dependency injection instead .

但是,您仍然可以加载一个 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.ConfigurationMicrosoft.Extensions.Configuration.Json包裹。更多配置选项 see the documentation .

关于c# - 从 .net 标准库中读取 appsettings.json,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50562798/

相关文章:

c# - 在 .net 4.5 中使用 ClientWebSocket 时如何设置 User-Agent 和 Referer header ?

c# - Jwt Bearer 和依赖注入(inject)

.net-core - .net 核心中的 XSD/架构验证解决方法?

c# - 如何在 Visual Studio 2015 中更改 ASP.NET Core 构建平台

docker - Identityserver4 openid-configuration 省略运行 nginx 反向代理的主机端口

c# - 找不到类型或命名空间列表<>

C#使用其他代码

razor - 如何使用没有 Controller 的 Razor Pages 填充下拉列表

c# - 如何在 C#/WPF 中以编程方式访问 Windows Media Player 库?

asp.net - .NET Core 2 - 创建具有存储库的 Controller 类的实例