dotnet config_error ai_generated true

Microsoft.Extensions.Options.OptionsValidationException: 发生配置验证错误。'MyOptions'成员的数据注释验证失败:'ApiKey'是必需的。

Microsoft.Extensions.Options.OptionsValidationException: A configuration validation error occurred. DataAnnotation validation failed for 'MyOptions' members: 'ApiKey' is required.

ID: dotnet/aspnetcore-options-validation-failure

其他格式: JSON · Markdown 中文 · English
90%修复率
87%置信度
1证据数
2023-04-12首次发现

版本兼容性

版本状态引入弃用备注
.NET 6.0 active
.NET 7.0 active
.NET 8.0 active
ASP.NET Core 6.0+ active

根因分析

ASP.NET Core使用数据注释(例如[Required])的选项验证在启动时通过ValidateOnStart()触发,但appsettings.json或环境变量中缺少或为空必需的配置键。

English

ASP.NET Core's options validation using DataAnnotations (e.g., [Required]) is triggered at startup via ValidateOnStart(), but the required configuration key is missing or empty in appsettings.json or environment variables.

generic

官方文档

https://learn.microsoft.com/en-us/aspnet/core/fundamentals/configuration/options?view=aspnetcore-8.0#options-validation

解决方案

  1. Add the missing configuration key to appsettings.json or environment variables with the correct path matching the options class hierarchy.
  2. If the value is optional, remove the [Required] attribute from the property and handle null checks in code.

无效尝试

常见但无效的做法:

  1. Adding a default value in the options class constructor to avoid null 60% 失败

    Validation is based on DataAnnotations attributes, not null checks; a default value does not satisfy [Required] if the config key is missing.

  2. Removing ValidateOnStart() to defer validation until first use 40% 失败

    The error moves to runtime, causing unexpected failures later; the root issue (missing config) remains.