处理 .Net Core AppSettings/configuration 中带句点的键名

Joe*_*moe 8 c# .net-core asp.net-core

考虑以下appsettings.json

{
  "Logging": {
    "LogLevel": {
      "Default": "Information",
      "Microsoft": "Warning",
      "Microsoft.Hosting.Lifetime": "Information"
    }
  },
  "AllowedHosts": "*",

  "NumberOfRetries": 5,
  "Option1": "abc",
  "Option2":  "def"

}
Run Code Online (Sandbox Code Playgroud)

为了读取NumberOfRetries以下类可以成功使用:

public class AppSettings
{
    public int NumberOfRetries { get; set; }
    public string Option1 { get; set; }
    public string Option2 { get; set; }
}
Run Code Online (Sandbox Code Playgroud)

Startup.cs 中包含以下代码:

    public Startup(IConfiguration configuration)
    {
        Configuration = configuration;
    }

    public IConfiguration Configuration { get; }

    // This method gets called by the runtime. Use this method to add services to the container.
    public void ConfigureServices(IServiceCollection services)
    {
        services.AddControllers();

        services.AddOptions();

        services.Configure<AppSettings>(Configuration);
    }
Run Code Online (Sandbox Code Playgroud)

现在,假设键名是Number.Of.Retries- NumberOfRetries,中间有句点。

如何AppSetings修改类(或方法本身)来支持这一点?无法在属性名称中准确添加句点。

Joe*_*moe 3

好吧,我明白了。

理想情况下我想像JsonPropertyName这样使用:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text.Json.Serialization;
using System.Threading.Tasks;

namespace WebAPICore
{
    public class AppSettings
    {
        [JsonPropertyName("Number.Of.Retries")]
        public int NumberOfRetries { get; set; }
        public string Option1 { get; set; }
        public string Option2 { get; set; }
    }
}
Run Code Online (Sandbox Code Playgroud)

但它不起作用。为什么?他们不使用 JSON 解析器吗?

所以我最终得到的解决方案如下所示:

    public Startup(IConfiguration configuration)
    {
        Configuration = configuration;
    }

    public IConfiguration Configuration { get; }

    // This method gets called by the runtime. Use this method to add services to the container.
    public void ConfigureServices(IServiceCollection services)
    {
        services.AddControllers();

        services.AddOptions();

        services.Configure<AppSettings>(Configuration); // This maps every key that matches existing property name

        services.PostConfigure<AppSettings>(appSettings =>// This maps keys where names don't match existing property names
        {
            appSettings.NumberOfRetries = Configuration.GetValue<int>("Number.Of.Retries");
        }); 
    }
Run Code Online (Sandbox Code Playgroud)