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.
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
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.
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.
Here is our
CustomBadRequest class which assigns error properties in the constructor.
public class CustomBadRequest : ValidationProblemDetails
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.
We can configure our newly created CustomBadRequest in Configure method in
Startup.cs class in two different ways.
ConfigureApiBehaviorOptions is an extension method on
IMvcBuilder interface. Any method that returns an
IMvcBuilder can call the
AddMvc() returns an
IMvcBuilder and we will plug our custom bad request here.
This will be convenient as we don’t chain the configuration here. We’ll be just using the generic configure method here.
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.