阅读 appsettings.{env}.json .NET 6 中的对象 API - 值为 NULL

Read appsettings.{env}.json objects in .NET 6 API - Values coming as NULL

我正在使用 .NET 6 创建 API。 我有基于环境的 appsettings.json 个文件。

我也在 launchSettings.json 中创建了 apt 配置文件。

我正在尝试使用 Options 模式来读取其中一个控制器内的 key/values。

我每次都得到 NULL 的值。

当我调试 Program.cs 文件时,我可以通过下面的代码行看到正确的值。

builder.Configuration.GetSection(key: "Config").Get<Config>();

请帮忙。使用的代码如下:

Program.cs:

var builder = WebApplication.CreateBuilder(args);
var configuration = builder.Configuration;

var env = Environment.GetEnvironmentVariable("ASPNETCORE_ENVIRONMENT");

configuration
    .AddJsonFile("appsettings.json", optional: true, reloadOnChange: true)
    .AddJsonFile($"appsettings.{env}.json", true, true);

builder.Configuration.GetSection(key: "Config").Get<Config>();

builder.Services.AddControllers();
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen();
builder.Services.AddScoped<IProductRepository, ProductRepository>();
builder.Services.AddSingleton<Config>();

Config.cs:

public class Config
    {
        public string Environment { get; set; }
        public string Type { get; set; }
    }

ProductsController.cs

    [Route("api/[controller]")]
    [ApiController]
    public class ProductsController : ControllerBase
    {
        private readonly IProductRepository _repository;
        private readonly Config _config;

        public ProductsController(IProductRepository repository,
            IOptions<Config> config)
        {
            _repository = repository;
            _config = config.Value;
        }

        [HttpGet]
        [Route("/configs")]
        public IActionResult GetConfigs()
        {
            var model = new { type = _config.Type, env = _config.Environment };
            return Ok(model);
        }

appsettings.json:

{
  "Logging": {
    "LogLevel": {
      "Default": "Information",
      "Microsoft.AspNetCore": "Warning"
    }
  },
  "AllowedHosts": "*",
  "Config": {
    "Environment": "local",
    "Type": "local Server"
  }
}

appsettings.Development.json:

{
  "Logging": {
    "LogLevel": {
      "Default": "Information",
      "Microsoft.AspNetCore": "Warning"
    }
  },
  "Config": {
    "Environment": "Development",
    "Type": "Development Server"
  }
}

appsettings.Staging.json:

{
  "Logging": {
    "LogLevel": {
      "Default": "Information",
      "Microsoft.AspNetCore": "Warning"
    }
  },
  "Config": {
    "Environment": "Staging",
    "Type": "Staging Server"
  }
}

launchSettings.json:

 "profiles": {
    "API - Development": {
      "commandName": "Project",
      "dotnetRunMessages": true,
      "launchBrowser": true,
      "launchUrl": "swagger",
      "applicationUrl": "https://localhost:7082;http://localhost:5082",
      "environmentVariables": {
        "ASPNETCORE_ENVIRONMENT": "Development"
      }
    },
    "API - Staging": {
      "commandName": "Project",
      "dotnetRunMessages": true,
      "launchBrowser": true,
      "applicationUrl": "https://localhost:5001;http://localhost:5000",
      "environmentVariables": {
        "ASPNETCORE_ENVIRONMENT": "Staging"
      }
    }
}

输出:

services.AddOptions<Config>()
    .Bind(configuration.GetSection("Config"))
    .ValidateDataAnnotations(); // optionally validate annotations

尝试使用 AddOptions,然后应该会绑定。

我认为您可能需要在 Services.Configure 中使用 configuration.GetSection,这意味着从 appsettings.json 的 Config 部分注册 Config 对象.

builder.Services.Configure<Config>(configuration.GetSection("Config"));

我认为您的问题在:

configuration
.AddJsonFile("appsettings.json", optional: true, reloadOnChange: true)
.AddJsonFile($"appsettings.{env}.json", true, true);

builder.Configuration.GetSection(key: "Config").Get<Config>();

builder.Services.AddControllers();
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen();
builder.Services.AddScoped<IProductRepository, ProductRepository>();
builder.Services.AddSingleton<Config>();

您当前正在获取一个部分 Config,然后在其上调用 Get<> 但从未将其应用于任何内容(注入)。看起来最后一行会这样做,但是这个函数没有参数来提供注入的东西。

你可以:

builder.Services.Configure<Config>(builder.Configuration.GetSection("Config"));