gpt4 book ai didi

.net - Configuration.GetSection 在 .net core (3.1) 中返回 null

转载 作者:行者123 更新时间:2023-12-03 21:57:13 26 4
gpt4 key购买 nike

我正在尝试使用“Configuation.GetSection”获取信息 appSettings.json 文件。但不知何故我无法得到这个。

这是代码

appSettings.Development.json:

{
"test": {
"a": "sdfs"
}

启动文件
var test = Configuration.GetSection("test");

我需要运行什么来从 appsettings.json 文件中获取信息。

enter image description here

enter image description here

请帮忙。提前致谢

最佳答案

我想我找到了上述问题的答案。我不确定我是对还是错。

我想从“apSettings.json”文件中获取设置并创建它的一个对象,然后将它与 DI 一起使用到我的 Controller 中。

为此,我现在使用这种方式。

在 ConfigureServices 方法中:

public void ConfigureServices(IServiceCollection services)
{
AppSettings _settings = new AppSettings();
services.AddControllersWithViews();
Configuration.GetSection("AppSettings").Bind(_settings);// bind is necessary
services.AddSingleton(_settings);
}

(注意:AppSettings 是自定义类,它将具有 appSettings.json 中提到的属性)

选项2:
这是从“appsettings.json”获取信息的第二个选项。
services.AddSingleton<AppSettings>(Configuration.GetSection("AppSettings").Get<AppSettings>();

关于.net - Configuration.GetSection 在 .net core (3.1) 中返回 null,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61382986/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com