DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Newsletter
Log In / Join
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Related

  • Revolutionizing Content Management
  • Architecting Scalable ASP.NET Core Web APIs With Abstract Factory Method and Onion Architecture
  • Building a Microservices API Gateway With YARP in ASP.NET Core Web API
  • Working With dotConnect for Oracle in ASP.NET Core

Trending

  • How to Keep AI Agents From Going Rogue Using Docker Sandbox
  • Part 2: Securing and Scaling Goose-to-Java Agent Traffic With agentgateway
  • Rebuilding Elasticsearch Under Load: Unsafe Watermarks and a Sampling Blind Spot
  • Data Integration Landscape 2026: Event Streaming, API, and Batch in the Era of Agentic AI

Draft This article hasn't been published, so readers can't see it.

In moderation This article is waiting for review, so readers can't see it yet.

Deleted This article has been deleted, so readers can't see it.

  1. DZone
  2. Coding
  3. Frameworks
  4. Customizing Automatic HTTP 400 Error Response in ASP.NET Core Web APIs

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.

By 
Karthik Chintala
·
Updated Apr. 30, 19 · Tutorial
Post on X (opens in a new tab) Share on LinkedIn (opens in a new tab)
47.3K Views

Join the DZone community Save articles, join the discussion, and download Refcards and Trend Reports with a free account.

Join for free Already a member? Log in

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.Image title

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.

ASP.NET .NET Web API ASP.NET Core

Published at DZone with permission of Karthik Chintala. See the original article here.

Opinions expressed by DZone contributors are their own.

Related

  • Revolutionizing Content Management
  • Architecting Scalable ASP.NET Core Web APIs With Abstract Factory Method and Onion Architecture
  • Building a Microservices API Gateway With YARP in ASP.NET Core Web API
  • Working With dotConnect for Oracle in ASP.NET Core

Partner Resources

×

Comments

Loading comments

The comments didn't load

Please try again in a moment.

Likes

Loading

The next likes didn't load. Please try again.

The likes didn't load

Please try again in a moment.

See who liked this

Log in or join DZone for free to see who liked this article.

Log in Join for free
  • RSS
  • X
  • Facebook

ABOUT US

  • About DZone
  • Support and feedback
  • Community research

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Core Program
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 3343 Perimeter Hill Drive
  • Suite 215
  • Nashville, TN 37211
  • [email protected]

Let's be friends:

  • RSS
  • X
  • Facebook