如果我有以下设置,有没有办法从内部请求设置
Program.cs
。
appsettings.json
:
{
"Settings": {
"UseMemory": false,
"Cors": {
"Origins": "*",
"Headers": "*",
"Methods": "*"
}
}
}
设置型号:
public class AppSettings
{
public bool? UseMemory { get; set; }
public CorsSettings? Cors { get; set; }
}
public class CorsSettings
{
public required string Origins { get; set; }
public required string Headers { get; set; }
public required string Methods { get; set; }
}
这些是我的尝试,但设置始终是
null
(在Program.Main
内)
var builder = WebApplication.CreateBuilder(args);
var appSettings = builder.Configuration.GetRequiredSection("Settings");
builder.Services.Configure<Models.AppSettings>(appSettings);
...
var settings = builder.Configuration.Get<Models.AppSettings>(); // { UseMemory: null, Cors: null }
var builder = WebApplication.CreateBuilder(args);
var settings = builder.Configuration.GetValue<Models.AppSettings>("Settings"); // null
var settingsText = builder.Configuration.GetValue<string>("Settings"); // null
这“有效”,但我希望找到一种方法将所有设置放在一个整洁的对象中:
var builder = WebApplication.CreateBuilder(args);
var settingsText = builder.Configuration.GetSection("Settings").GetValue<string>("UseMemory"); // false