Annotating the controllers with ApiController attribute in ASP.NET Core 2.1 or higher will enable the behavioral options for the API’s. These behavioral options include automatic HTTP 400 responses as well.

In this post, we’ll see how we can customize the default error response from the ASP.NET Core Web API.

Default error response

If you are creating a new default ASP.NET Core web API project, then you’d see the ValuesController.cs file in the project. Otherwise, create a Controller and create an action method to a parameter to test the automatic HTTP 400 responses.

If you are creating a custom API for yourself you’d need to annotate the controller with [ApiController] attribute. Otherwise, the default 400 responses won’t work.

I’ll go with the default ValuesController for now. We already have the Get action with id passed in as the parameter.

// GET api/values/5 [HttpGet(“{id}”)] public ActionResult Get(int id) { return “value”; }

Let’s try to pass in a string for the id parameter for the Get action through Postman.

This is the default error response returned by the API.

Notice that we didn’t have the ModelState checking in our Get action method this is because ASP.NET Core did it for us as we have the [ApiController] attribute on top of our controller.

Customizing the error response

To modify the error response we need to make use of the InvalidModelStateResponseFactory property.

InvalidModelStateResponseFactory is a delegate which will invoke the actions annotated with ApiControllerAttribute to convert invalid ModelStateDictionary into an IActionResult.

The default response type for HTTP 400 responses is ValidationProblemDetails class. So, we will create a custom class which inherits ValidationProblemDetails class and define our custom error messages.

CustomBadRequest class

Here is our CustomBadRequest class which assigns error properties in the constructor.

public class CustomBadRequest : ValidationProblemDetails { public CustomBadRequest(ActionContext context) { Title = “Invalid arguments to the API”; Detail = “The inputs supplied to the API are invalid”; Status = 400; ConstructErrorMessages(context); Type = context.HttpContext.TraceIdentifier; } private void ConstructErrorMessages(ActionContext context) { foreach (var keyModelStatePair in context.ModelState) { var key = keyModelStatePair.Key; var errors = keyModelStatePair.Value.Errors; if (errors != null && errors.Count > 0) { if (errors.Count == 1) { var errorMessage = GetErrorMessage(errors[0]); Errors.Add(key, new[] { errorMessage }); } else { var errorMessages = new string[errors.Count]; for (var i = 0; i < errors.Count; i++) { errorMessages[i] = GetErrorMessage(errors[i]); } Errors.Add(key, errorMessages); } } } } string GetErrorMessage(ModelError error) { return string.IsNullOrEmpty(error.ErrorMessage) ? “The input was not valid.” : error.ErrorMessage; } }

I’m using ActionContext as a constructor argument as we can have more information about the action. I’ve used the ActionContext as I’m using the TraceIdentifier from the HttpContext . The Action context will have route information, HttpContext, ModelState, ActionDescriptor.

You could pass in just the model state in the action context at least for this bad request customization. It is up to you.

Plugging the CustomBadRequest in the configuration

We can configure our newly created CustomBadRequest in Configure method in Startup.cs class in two different ways.

using ConfigureApiBehaviorOptions off AddMvc()

ConfigureApiBehaviorOptions is an extension method on IMvcBuilder interface. Any method that returns an IMvcBuilder can call the ConfigureApiBehaviorOptions method.

public static IMvcBuilder ConfigureApiBehaviorOptions(this IMvcBuilder builder, Action setupAction);

The AddMvc() returns an IMvcBuilder and we will plug our custom bad request here.

services.AddMvc() .SetCompatibilityVersion(CompatibilityVersion.Version_2_2) .ConfigureApiBehaviorOptions(options => { options.InvalidModelStateResponseFactory = context => { var problems = new CustomBadRequest(context); return new BadRequestObjectResult(problems); }; });

using the generic Configure method

This will be convenient as we don’t chain the configuration here. We’ll be just using the generic configure method here.

services.Configure(a => { a.InvalidModelStateResponseFactory = context => { var problemDetails = new CustomBadRequest(context); return new BadRequestObjectResult(problemDetails) { ContentTypes = { “application/problem+json”, “application/problem+xml” } }; }; });

Testing the custom bad request

That’s it for configuring the custom bad request, let’s run the app now.

You can see the customized HTTP 400 error messages we’ve set in our custom bad request class showing up.

Image Credits