gpt4 book ai didi

c# - 如何在 DI 设置期间自动验证 appSettings.json 文件中的配置值?

转载 作者:行者123 更新时间:2023-12-03 14:42:03 32 4
gpt4 key购买 nike

我在 .NET Core 项目的 appSettings.json 文件中添加了配置。为了简单起见,我以数据库设置为例。所以在设置文件中你会有

{
"Database": {
"Host": "localhost",
"Port": 1234,
"Database": "myDb",
"Username": "username",
"Password": "pw",
"EnablePooling": true
}
}
在 Startup.cs 文件中配置服务时,我希望通过依赖注入(inject)来访问这些设置。用于此的数据模型是
public class DatabaseSettings
{
public string Host { get; set; }
public ushort Port { get; set; }
public string Database { get; set; }
public string Username { get; set; }
public string Password { get; set; }
public bool EnablePooling { get; set; }
}
我这样配置
private void SetupSettings(IServiceCollection services)
{
ServiceProvider serviceProvider = services.BuildServiceProvider();
IConfiguration configuration = serviceProvider.GetService<IConfiguration>();

IConfigurationSection databaseConfigurationSection = configuration.GetSection("Database");
services.Configure<DatabaseSettings>(databaseConfigurationSection);
}
最后我想验证这些设置。我知道我可以创建一个验证器类来实现 IValidateOptions界面。
public class DatabaseSettingsValidator : IValidateOptions<DatabaseSettings>
{
private readonly IList<string> failures;

public DatabaseSettingsValidator()
{
failures = new List<string>();
}

public ValidateOptionsResult Validate(string databaseSettingsName, DatabaseSettings databaseSettings)
{
if (databaseSettings == null)
failures.Add($"{databaseSettingsName} are required.");

if (string.IsNullOrEmpty(databaseSettings?.Host))
failures.Add($"{nameof(databaseSettings.Host)} must not be empty.");

if (string.IsNullOrEmpty(databaseSettings?.Database))
failures.Add($"{nameof(databaseSettings.Database)} must not be empty.");

if (failures.Any())
return ValidateOptionsResult.Fail(failures);

return ValidateOptionsResult.Success;
}
}
但是我必须创建这个类并调用 Validate吗?我自己的方法?也许有类似这个示例代码的东西?
.
services.ValidateConfiguration<IOptions<DatabaseSettings>, DatabaseSettingsValidator>();
因此,您传入配置的设置和要使用的验证器。

最佳答案

but I'm struggling with two questions:

Is there a way I can collect all failures instead of returning afterone? So you would get a list of failures instead of having to fix oneby one.

Do I have to create this class and call the Validate method on my own?Maybe there is something like this sample code?

services.ValidateConfiguration<IOptions,DatabaseSettingsValidator>(); So you pass in the configured settingsand the validator to use.


是的,我们可以收集所有失败列表并立即显示它们,我们还可以创建一个包含 Validate 方法的类。请检查以下步骤:
首先,由于类名是“ DatabaseSettings ”,最好将配置节名称设置为与类名相同:
{
"DatabaseSettings": {
"Host": "localhost",
"Port": 1234,
"Database": "myDb",
"Username": "username",
"Password": "pw",
"EnablePooling": true
}
}
[注意] 如果使用不同的名称,该值可能不会映射到数据库设置类,因此在验证数据时,它们都为空。
其次,使用 Data Annotations 方法将验证规则添加到模型属性中。
public class DatabaseSettings
{
[Required]
public string Host { get; set; }
[Required]
public ushort Port { get; set; }
[Required]
public string Database { get; set; }
[Required]
public string Username { get; set; }
[Required]
public string Password { get; set; }
[Required]
public bool EnablePooling { get; set; }
}
第三,创建一个包含 ConfigureAndValidate 方法的 ServiceCollectionExtensions 类:
public static class ServiceCollectionExtensions
{
public static IServiceCollection ConfigureAndValidate<T>(this IServiceCollection @this,
IConfiguration config) where T : class
=> @this
.Configure<T>(config.GetSection(typeof(T).Name))
.PostConfigure<T>(settings =>
{
var configErrors = settings.ValidationErrors().ToArray();
if (configErrors.Any())
{
var aggrErrors = string.Join(",", configErrors);
var count = configErrors.Length;
var configType = typeof(T).Name;
throw new ApplicationException(
$"Found {count} configuration error(s) in {configType}: {aggrErrors}");
}
});
}
然后,注册 ConfigureAndValidate 服务:
public void ConfigureServices(IServiceCollection services)
{
services.ConfigureAndValidate<DatabaseSettings>(Configuration);
}
最后,获取异常列表。
public class HomeController : Controller
{
private readonly DatabaseSettings_settings;

public HomeController(IOptions<DatabaseSettings> settings)
{
_settings = settings.Value; // <-- FAIL HERE THROW EXCEPTION
}
}
然后,像这样的测试结果(我从 appSettings.json 中删除了主机和用户名):
enter image description here
更多详细信息,可以查看这篇博客: Validating configuration in ASP.NET Core

关于c# - 如何在 DI 设置期间自动验证 appSettings.json 文件中的配置值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63366146/

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