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
版本兼容性
| 版本 | 状态 | 引入 | 弃用 | 备注 |
|---|---|---|---|---|
| .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.
官方文档
https://learn.microsoft.com/en-us/aspnet/core/fundamentals/configuration/options?view=aspnetcore-8.0#options-validation解决方案
-
Add the missing configuration key to appsettings.json or environment variables with the correct path matching the options class hierarchy.
-
If the value is optional, remove the [Required] attribute from the property and handle null checks in code.
无效尝试
常见但无效的做法:
-
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.
-
Removing ValidateOnStart() to defer validation until first use
40% 失败
The error moves to runtime, causing unexpected failures later; the root issue (missing config) remains.