gpt4 book ai didi

c# - 在 .Net Core AppSettings/配置中处理带句点的键名

转载 作者:行者123 更新时间:2023-12-04 13:38:21 28 4
gpt4 key购买 nike

考虑关注 appsettings.json :

{
"Logging": {
"LogLevel": {
"Default": "Information",
"Microsoft": "Warning",
"Microsoft.Hosting.Lifetime": "Information"
}
},
"AllowedHosts": "*",

"NumberOfRetries": 5,
"Option1": "abc",
"Option2": "def"

}

为了阅读 NumberOfRetries以下类可以成功使用:
public class AppSettings
{
public int NumberOfRetries { get; set; }
public string Option1 { get; set; }
public string Option2 { get; set; }
}

在 Startup.cs 中使用以下代码:
    public Startup(IConfiguration configuration)
{
Configuration = configuration;
}

public IConfiguration Configuration { get; }

// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{
services.AddControllers();

services.AddOptions();

services.Configure<AppSettings>(Configuration);
}

现在,假设 key 名称是 Number.Of.Retries而不是 NumberOfRetries - 中间有句号。

怎么会 AppSetings类(或方法本身)被修改以支持它?不能在属性名称中准确放置句点。

最佳答案

我明白你的意思,我快速查了一下,有能力提供关于如何配置你的选项的自定义逻辑。我做了一个快速原型(prototype)...

void Main()
{
string json = @"{
""Logging"": {
""LogLevel"": {
""Default"": ""Information"",
""Microsoft"": ""Warning"",
""Microsoft.Hosting.Lifetime"": ""Information""

}
},
""AllowedHosts"": ""*"",
""Number.Of.Retries"": 5
}";

using (var doc = System.Text.Json.JsonDocument.Parse(json, new JsonDocumentOptions { AllowTrailingCommas = true, CommentHandling = JsonCommentHandling.Skip } ))
{
using(var stream = new MemoryStream())
{
using (var writer = new Utf8JsonWriter(stream))
{
doc.WriteTo(writer);
writer.Flush();
}

stream.Position = 0;

// Usable code here
IConfigurationRoot configuration = new ConfigurationBuilder().AddJsonStream(stream).Build();

var services = new ServiceCollection();

services.AddOptions<AppSettings>();

// There is an option to configure it manually here, if it does not fit the convention
services.Configure<AppSettings>((options) =>
{
options.NumberOfRetries = configuration.GetValue<int>("Number.Of.Retries");
});

var container = services.BuildServiceProvider();

using (var scope = container.CreateScope())
{
var appSettings = scope.ServiceProvider.GetRequiredService<IOptions<AppSettings>>();

Console.WriteLine(appSettings.Value.NumberOfRetries);
}
}
}
}

public class AppSettings
{
public int NumberOfRetries { get; set; }
}


如果您有特定的设置模式,您可以为自己的“约定”创建自定义设置绑定(bind)器,我提供了一个非常基本的示例,它处理 '.'在设置中。


void Main()
{
string json = @"{
""Logging"": {
""LogLevel"": {
""Default"": ""Information"",
""Microsoft"": ""Warning"",
""Microsoft.Hosting.Lifetime"": ""Information""

}
},
""AllowedHosts"": ""*"",
""Number.Of.Retries"": 5
}";

using (var doc = System.Text.Json.JsonDocument.Parse(json, new JsonDocumentOptions { AllowTrailingCommas = true, CommentHandling = JsonCommentHandling.Skip } ))
{
using(var stream = new MemoryStream())
{
using (var writer = new Utf8JsonWriter(stream))
{
doc.WriteTo(writer);
writer.Flush();
}

stream.Position = 0;

// Usable code here
IConfigurationRoot configuration = new ConfigurationBuilder().AddJsonStream(stream).Build();

var services = new ServiceCollection();
services.AddOptions<AppSettings>();
services.AddSingleton<IConfiguration>(configuration);
services.ConfigureOptions<CustomConfigureOptions>();

var container = services.BuildServiceProvider();

using (var scope = container.CreateScope())
{
var appSettings = scope.ServiceProvider.GetRequiredService<IOptions<AppSettings>>();

Console.WriteLine(appSettings);
}
}
}
}

public class AppSettings
{
public int NumberOfRetries { get; set; }
}

public class CustomConfigureOptions : IConfigureOptions<AppSettings>
{
private readonly IConfiguration configuration;

public CustomConfigureOptions(IConfiguration configuration)
{
this.configuration = configuration;
}

public void Configure(AppSettings options)
{
foreach(var pair in configuration.AsEnumerable())
{
foreach(var property in typeof(AppSettings).GetProperties())
{
if (property.Name.Equals(pair.Key.Replace(".", "")))
{
property.SetValue(options, configuration.GetValue(property.PropertyType, pair.Key));
}
}
}
}
}


关于c# - 在 .Net Core AppSettings/配置中处理带句点的键名,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60470583/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com