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

- **ID:** `dotnet/aspnetcore-options-validation-failure`
- **领域:** dotnet
- **类别:** config_error
- **验证级别:** ai_generated
- **修复率:** 90%

## 根因

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

## 版本兼容性

| 版本 | 状态 | 引入 | 弃用 |
|------|------|------|------|
| .NET 6.0 | active | — | — |
| .NET 7.0 | active | — | — |
| .NET 8.0 | active | — | — |
| ASP.NET Core 6.0+ | active | — | — |

## 解决方案

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.
   ```

## 无效尝试

- **Adding a default value in the options class constructor to avoid null** — Validation is based on DataAnnotations attributes, not null checks; a default value does not satisfy [Required] if the config key is missing. (60% 失败率)
- **Removing ValidateOnStart() to defer validation until first use** — The error moves to runtime, causing unexpected failures later; the root issue (missing config) remains. (40% 失败率)
