无法使用 Asp.Net Core 3 中的命名选项 read/bind 使用强类型 class 配置设置

Unable to read/bind configuration settings with strongly-typed class using Named Options in Asp.Net Core 3

我无法使用命名选项将 appsettings.json 中的配置设置绑定到强类型 class。

appsettings.json

"CJSettings": {
    "Normal": {
      "CSSUrl": "https://css.mydomain.com/main.min.css",
      "LogoName": "mysite-logo.png"
    },
    "WL": {
      "CSSUrl": "https://css.mydomain.com/main_wl.min.css",
      "LogoName": "mysite-WL-logo.png"
    },
    "SEG": {
      "CSSUrl": "https://css.mydomain.com/main_seg.min.css",
      "LogoName": "mysite-seg-logo.png"
    }}

CJSettings.cs

public class CJSettings
{
    public string CSSUrl { get; set; }
    public string LogoName { get; set; }
}

Startup.cs

services.Configure<CJSettings>("Normal", configuration.GetSection("CJSettings.Normal"));
services.Configure<CJSettings>("WL", configuration.GetSection("CJSettings.WL"));
services.Configure<CJSettings>("SEG", configuration.GetSection("CJSettings.SEG"));

NormalService.cs

我正在尝试使用名称读取配置数据的服务。但没有成功。

public class NormalService : INormalService
{
    private readonly CJSettings cjSettings;

    public NormalService(IOptionsMonitor<CJSettings> options)
    {
        this.cjSettings = options.Get("Normal");    //getting null values for both properties
    }
}

正如您在上面看到的,我尝试使用名称 "Normal" 读取数据,但我得到的 CJSettings 对象的两个属性都为空值。

请帮我解决这个问题...谢谢

我不知道为什么你的代码不起作用。我可以建议以下我一直在使用的解决方案:

public class CJSettings
{
    public UrlSettings Normal { get; set; }
    public UrlSettings WL { get; set; }
    public UrlSettings SEG { get; set; }
}

public class UrlSettings
{
    public string CSSUrl { get; set; }
    public string LogoName { get; set; }
}

注册选项和服务:

    public void ConfigureServices(IServiceCollection services)
    {
        services.Configure<CJSettings>(Configuration.GetSection(nameof(CJSettings)));
        services.AddTransient<INormalService, NormalService>();

        // the rest of your code
    }

然后将选项注入到服务的构造函数中:

public class NormalService : INormalService
{
    private readonly CJSettings cjSettings;

    public NormalService(IOptions<CJSettings> options)
    {
        this.cjSettings = options.Value ?? throw new ArgumentNullException(nameof(CJSettings));
    }
}

这应该有效。我查过了。

已更新

其实你的代码没问题。您只需要在 GetSection 方法的关键参数中使用冒号而不是点:

services.Configure<CJSettings>("Normal", Configuration.GetSection("CJSettings:Normal"));
services.Configure<CJSettings>("WL", Configuration.GetSection("CJSettings:WL"));
services.Configure<CJSettings>("SEG", Configuration.GetSection("CJSettings:SEG"));