嵌套类属性无法从配置ASP.NET Core中正确填充

时间:2019-03-25 15:04:19

标签: asp.net asp.net-core asp.net-core-2.0

我需要在ASP.NET Core 2.2中的appsetting.json中填写以下信息。

"SiteSetting": {
    "JwtSetting": {
      "SecretKey": "LongerThan-16Char-SecretKey",
      "Issuer": "MyWebsite",
      "Audience": "MyWebsite",
      "NotBeforeMinutes": "0",
      "ExpirationMinutes": "60"
    }
}

这是我的SiteSetting课:

public class SiteSetting
{
    public JwtSetting JwtSettings { get; set; }
}

public class JwtSetting
{
    public string SecretKey { get; set; }
    public string Issuer { get; set; }
    public string Audience { get; set; }
    public int NotBeforeMinutes { get; set; }
    public int ExpirationMinutes { get; set; }
}

我正在Startup.cs中使用此代码填充SiteSetting

public IConfiguration Configuration { get; }

    private SiteSetting _siteSetting;

    public Startup(IConfiguration configuration)
    {
        Configuration = configuration;
        _siteSetting = configuration.GetSection(nameof(SiteSetting)).Get<SiteSetting>();
    }

    public void ConfigureServices(IServiceCollection services)
    {
        services.Configure<SiteSetting>(Configuration.GetSection(nameof(SiteSetting)));
    }

但是当我调试它时,_siteSetting为空。

出什么问题了?我该如何解决这个问题?

1 个答案:

答案 0 :(得分:1)

AppSettings.json中,您定义了JwtSetting,但在SiteSetting类中,您将其命名为JwtSetting s 。为了自动进行解析,类属性名称和JSON属性键应该完全相同。

这样更改您的AppSettings.json即可正常工作:

"SiteSetting": {
    "JwtSettings": {
      "SecretKey": "LongerThan-16Char-SecretKey",
      "Issuer": "MyWebsite",
      "Audience": "MyWebsite",
      "NotBeforeMinutes": "0",
      "ExpirationMinutes": "60"
    }
}