Customizing Automatic HTTP 400 Error Response in ASP.NET Core Web APIs
In this post, we'll see how we can customize the default error response from the ASP.NET Core Web API.
Join the DZone community and get the full member experience.
Join For FreeAnnotating 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 must 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<string> 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 that inherits ValidationProblemDetails
class and define our custom error messages.
CustomBadRequest Class
Here is our CustomBadRequest
class, which assigns error properties in the construct
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's 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<ApiBehaviorOptions> 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<ApiBehaviorOptions>(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.
Let me know your thoughts in the comments.
Published at DZone with permission of Karthik Chintala. See the original article here.
Opinions expressed by DZone contributors are their own.
Comments