我正在使用 .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"
}
}
}
最佳答案
我认为您可能需要在 Services.Configure
中使用 configuration.GetSection
这意味着从 appsettings.json 的 Config
部分注册 Config
对象。
builder.Services.Configure<Config>(configuration.GetSection("Config"));
关于c# - 读取 .NET 6 API 中的 appsettings.{env}.json 对象 - 值为 NULL,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/72015380/