如何禁用不可为空属性的模型属性验证?

cre*_*mor 5 fluentvalidation asp.net-core asp.net-core-6.0

我在 ASP.NET Core 6 Web API 项目中使用FluentValidation 。这对于大多数情况都适用,因此:

  • 请求正文 JSON 语法验证由 ASP.NET Core 完成。
  • 请求对象属性验证由 FluentValidation 完成。

但有一个具体情况是有问题的:

  • 如果请求类型包含不可为 null 的属性(例如,string而不是string?)并且请求对象包含其 null 值,则验证由 ASP.NET Core 完成(但应由 FluentValidation 完成)。

我当前的解决方法是注释所有不可为空的属性,[ValidateNever]以便 ASP.NET Core 忽略它们,但这并不好。

有没有办法禁用不可为空属性的 ASP.NET Core 模型属性验证?

注意:我无法完全禁用 ASP.NET Core 验证,因为那样它甚至不会返回 JSON 语法错误的验证错误结果。

小智 9

尝试设置如下:

builder.Services.AddControllersWithViews(options => options.SuppressImplicitRequiredAttributeForNonNullableReferenceTypes = true);
Run Code Online (Sandbox Code Playgroud)

该问题已在本文档中进行了解释: https://learn.microsoft.com/en-us/dotnet/api/microsoft.aspnetcore.mvc.mvcoptions.suppressimplicitrequiredattributefornonnullablereferencetypes ?view=aspnetcore-6.0