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

标签 c# json api .net-6.0

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

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

我正在尝试使用 Options 模式来读取其中一个 Controller 内的键/值。

我每次都得到 NULL 的值。

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

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

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

程序.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>();

配置文件:

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"
      }
    }
}

输出: enter image description here

最佳答案

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

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

关于c# - 读取 .NET 6 API 中的 appsettings.{env}.json 对象 - 值为 NULL,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/72015380/

相关文章:

c# - 使用 C# 确定输入到文本框中的字符数

c# - 工具提示或类似的东西在 WPF 中随光标移动

c# - 使用linq获取最小值和最大值

c - 为什么 grep 给出 "Binary file (standard input) matches"?

python - 请求 - 无法在 JSON 正文中以 ISO 8601 格式发布日期

json - 如何从 json api 中省略工件

C# JsonConvert - 具有多种类型的列表列表

ios - 从 json 循环数组

javascript - 通过json访问一个URL,在chrome中可以通过提供User/Pass打开

Python 删除嵌套的 JSON 键或将键与值组合