How to disable the model property validation of not-nullable properties?
Asked Answered
C

1

6

I'm using FluentValidation in an ASP.NET Core 6 Web API project. This works fine for most cases, so:

  • Request body JSON syntax validation is done by ASP.NET Core.
  • Request object property validation is done by FluentValidation.

But there is one specific case that is problematic:

  • If the request type contains a not-nullable property (e.g. string instead of string?) and the request object contains a null value for it, validation is done by ASP.NET Core (but should be done by FluentValidation).

My current workaround is to annotate all that not-nullable properties with [ValidateNever] so that ASP.NET Core ignores them, but this is not nice.

Is there a way to disable ASP.NET Core model property validation of not-nullable properties?

Note: I can't disable ASP.NET Core validation completely because then it won't even return validation error results for JSON syntax errors.

Comity answered 6/7, 2022 at 12:26 Comment(0)
D
10

try to set as below :

builder.Services.AddControllersWithViews(options => options.SuppressImplicitRequiredAttributeForNonNullableReferenceTypes = true);

The problem has been explained in this document: https://learn.microsoft.com/en-us/dotnet/api/microsoft.aspnetcore.mvc.mvcoptions.suppressimplicitrequiredattributefornonnullablereferencetypes?view=aspnetcore-6.0

Dread answered 6/7, 2022 at 17:54 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.