从AppSettings.json读取ASP.NET CORE

问题描述 投票:0回答:2
I创建了一个简单的ASP.NET Core 6 MVC应用程序,其中我只是从

appsettings.json

文件读取值。
在我的

appsettings

中,我创建了两个部分,

SectionA
SectionB

i还创建了一个类,以映射此值与类属性:
这是我的

{ "SectionA": { "SectionASubItem1": "test value", "SectionASubItem2": "test value2" }, "SectionB": { "SectionBSubItem1": "test value", "SectionBSubItem2": "test value2" } }

课的样子:

MyConfiguration

public class MyConfiguration
{
    public SectionA SectionA { get; set; }
    public SectionB SectionB { get; set; }
}

public class SectionA
{
    public string SectionASubItem1 { get; set; }
    public string SectionASubItem2 { get; set; }
}

public class SectionB
{
    public string SectionBSubItem1 { get; set; }
    public string SectionBSubItem2 { get; set; }
}
类i创建了一个可变类型的

program.cs

我存储JSON文件属性的变量类型:
IConfigurationRoot

绘制这样的部分:
var myConfiguration = new ConfigurationBuilder()
    .SetBasePath(Directory.GetCurrentDirectory())
    .AddJsonFile("appsettings.json", optional: true, reloadOnChange: true)
    .Build();

问题是当我在控制器内部阅读
builder.Services.Configure<SectionA>(myConfiguration.GetSection("SectionA"));
builder.Services.Configure<SectionB>(myConfiguration.GetSection("SectionB"));

sectionA

时,我会变得无效。因此,我没有从JSON文件中获得值。
sectionB

设置您的
c# asp.net-core .net-core .net-6.0
2个回答
0
投票
喜欢:

appsetting.json

然后在
"MyConfiguration": {
    "SectionA": {
      "SectionASubItem1": "test value AAAAAA",
      "SectionASubItem2": "test value2 AAAA"
    },
    "SectionB": {
      "SectionBSubItem1": "test value BBBBBB",
      "SectionBSubItem2": "test value2 BBBBBB"
    }
  }
中以这样的配置:

Program.cs

最重要的一点是不要在构造函数中,您需要使用
builder.Services.Configure<SectionB>(myConfiguration.GetSection("MyConfiguration"));
来设置值。

new MyConfiguration()

然后您可以在_configuration中获得值:

您可以做到这一点 在appsettings.jsonenter image description here dependency injection


0
投票

private readonly IOptions<MyConfiguration> _configuration; public WeatherForecastController(IOptions<MyConfiguration> configuration) { _configuration= configuration; }

然后

"test": { "MyConfiguration": { "SectionA": { "SectionASubItem1": "test value", "SectionASubItem2": "test value2" }, "SectionB": { "SectionBSubItem1": "test value", "SectionBSubItem2": "test value2" } } }
最好使用ioptions,ioptionssnapshot或ioptionsMonitor.

iOptionsMonitor与Ioptionssnapshot

之间的差异
    

如果从课堂使用 您应该在控制器中进行ICONFIGURATION,然后传递到课堂 用于样品

builder.Services.Configure<MyConfiguration>(myConfiguration.GetSection("test:MyConfiguration"));

最新问题
© www.soinside.com 2019 - 2025. All rights reserved.