Home > Mobile >  How to disable the model property validation of not-nullable properties?
How to disable the model property validation of not-nullable properties?

Time:07-11

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.

CodePudding user response:

try to set as below :

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

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

  • Related