.Net Core Override Automatic Model Validation

Using .net core 2.1 framework I created a new api post endpoint. The endpoint returned a complex object with the capacity to indicate the outcome of the request. The endpoint accepted a complex object as the single parameter. The complex object included properties decorated with data annotations to trigger validation. No custom validators were used at this point.

I created unit tests for the api endpoint using the .net core TestHost framework. The first test would post a complex model to the endpoint and the expected outcome was a validation failure due to missing required model properties.

Unexpectedly the model was validated by the model binder. This is new functionality introduced in .net core 2.1. It can be a useful addition for those creating simple enpoints and forgetting to validate. However in this case it caused issues as the return message was not in the expected format.

To stop the model binder validation simply add the following configuration change to the startup.cs file of the api.

public void ConfigureServices(IServiceCollection services)
{
	services.Configure(opt =>
	{
		opt.SuppressModelStateInvalidFilter = true;
	});
}