Correct way to disable model validation in ASP.Net Core 2 MVC

 services.Configure<ApiBehaviorOptions>(options =>
        {
            options.SuppressModelStateInvalidFilter = true;
        });

should disable automatic model state validation.


Use this extension method:

public static IServiceCollection DisableDefaultModelValidation(this IServiceCollection services)
{
  ServiceDescriptor serviceDescriptor = services.FirstOrDefault<ServiceDescriptor>((Func<ServiceDescriptor, bool>) (s => s.ServiceType == typeof (IObjectModelValidator)));
  if (serviceDescriptor != null)
  {
    services.Remove(serviceDescriptor);
    services.Add(new ServiceDescriptor(typeof (IObjectModelValidator), (Func<IServiceProvider, object>) (_ => (object) new EmptyModelValidator()), ServiceLifetime.Singleton));
  }
  return services;
}


public class EmptyModelValidator : IObjectModelValidator
{
  public void Validate(ActionContext actionContext, ValidationStateDictionary validationState, string prefix, object model)
  {
  }
}

Ussage:

public void ConfigureServices(IServiceCollection services)
{
    services.DisableDefaultModelValidation();
}

As of aspnet core 3.1, this is how you disable model validation as seen in docs:

First create this NullValidator class:

public class NullObjectModelValidator : IObjectModelValidator
{
    public void Validate(ActionContext actionContext,
        ValidationStateDictionary validationState, string prefix, object model)
    {

    }
}

Then use it in place of the real model validator:

services.AddSingleton<IObjectModelValidator, NullObjectModelValidator>();

Note that this only disable Model validation, you'll still get model binding errors.


You should consider to use the ValidateNeverAttribute, which is nearly undocumented and well hidden by Microsoft.

[ValidateNever]
public class Entity 
{
....
}

This gives you fine grained control over which entities to validate and which not.