如何正确地将 appsettings.json 中的配置对象绑定到用户对象

Arb*_*æde 2 c# asp.net-core

我在 .net Core 1.1 上启动了一些基本项目,我希望将一些属性从 appsettings.json 映射到对象,但我可能无法理解正确的名称约定或一些非常基本的内容

关于MSDN使用选项和配置对象部分,使用它非常容易。我将下一行添加到 appsettings.json

{
  "Logging": {
    "IncludeScopes": false,
    "LogLevel": {
      "Default": "Warning"
    }
  },

  "XXXOptions": {
    "X1": {
      "AppId": "11",
      "AppCode": "22"
    },
    "X2": {
      "AppId": "",
      "AppCode": ""
    }
  }
}
Run Code Online (Sandbox Code Playgroud)

我添加了自定义类

 public class XXXOptions
    {
        public XXXOptions()
        {
        }
        public X1 X1{ get; set; }
        public X2 X2{ get; set; }
    }

    public class X1
    {
        public int AppId { get; set; }
        public int AppCode { get; set; }
    }

    public class X2
    {
        public int AppId { get; set; }
        public int AppCode { get; set; }
    }
Run Code Online (Sandbox Code Playgroud)

我将下一个代码添加到 Startup.cs

  public void ConfigureServices(IServiceCollection services)
        {
            // Adds services required for using options.
            services.AddOptions();

            // Register the IConfiguration instance which MyOptions binds against.
            services.Configure<XXXOptions>(Configuration);

            // Add framework services.
            services.AddMvc();
        }

 public class XXXController : Controller
    {
        private readonly XXXOptions _options;
        public XXXController(IOptions<XXXOptions> optionsAccessor)
        {
            _options = optionsAccessor.Value;
        }

        public IActionResult Index()
        {
            var option1 = _options.X1;
            return Content($"option1 = {option1.AppCode}, option2 = {option1.AppId}");
            return View();
        }
    }
Run Code Online (Sandbox Code Playgroud)

optionsAccessor.Value - XXXController 构造函数中的值包含空值。

但框架似乎在配置属性内的 JsonConfigurationProvider 处显示映射值

有任何想法吗?

Moh*_*our 7

ConfigureServices在方法改变中:

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

services.Configure<XXXOptions>(Configuration.GetSection("XXXOptions"));
Run Code Online (Sandbox Code Playgroud)