dotnet config_error ai_generated true

Microsoft.Extensions.Options.OptionsValidationException: 发生配置验证错误。成员 'ConnectionString' 的数据注释验证失败,错误信息:'ConnectionString 字段是必填的。'

Microsoft.Extensions.Options.OptionsValidationException: A configuration validation error occurred. DataAnnotation validation failed for members: 'ConnectionString' with error: 'The ConnectionString field is required.'

ID: dotnet/aspnet-core-options-validation-failure

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

版本兼容性

版本状态引入弃用备注
.NET 7.0 active — — —
.NET 8.0 active — — —
Microsoft.Extensions.Options.DataAnnotations 7.0.0 active — — —
Microsoft.Extensions.Options.DataAnnotations 8.0.0 active — — —

根因分析

当应用程序启动通过 DataAnnotations 验证配置对象且 appsettings.json 或环境变量中缺少必需属性或属性无效时,选项验证失败。

English

Options validation fails when an application startup validates configuration objects via DataAnnotations and a required property is missing or invalid 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. 确保 appsettings.json 或环境变量中存在所需的配置键。例如,在 appsettings.json 中添加:'"MyOptions": { "ConnectionString": "Server=myServer;Database=myDB;" }' 或设置环境变量 'MyOptions__ConnectionString' 为有效值。
  2. 如果该属性是可选的,请从选项类中移除 '[Required]' 属性并在代码中处理 null 值,或在配置中使用 'options.DefaultValue = "..."' 提供默认值。

无效尝试

常见但无效的做法:

  1. 85% 失败

    Removing the 'ValidateDataAnnotations()' call in services configuration suppresses the error but bypasses safety checks, potentially causing runtime issues.

  2. 70% 失败

    Adding a default value to the property in the options class may hide the error if the default is invalid, leading to silent failures.

  3. 60% 失败

    Only checking appsettings.json while the value is overridden by environment variables with empty string can still trigger validation failure.