ASP.NET 从 appsettings 获取整个对象

问题描述 投票:0回答:1

如果我有以下设置,有没有办法从内部请求设置

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
c# asp.net configuration appsettings
1个回答
0
投票

下面应该可以解决问题。

var appSettings = builder.Configuration.GetRequiredSection("Settings").Get<AppSettings>();

© www.soinside.com 2019 - 2024. All rights reserved.