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
Over 2 million developers have joined DZone.
Log In / Join
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Zones

Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks

Last call! Secure your stack and shape the future! Help dev teams across the globe navigate their software supply chain security challenges.

Modernize your data layer. Learn how to design cloud-native database architectures to meet the evolving demands of AI and GenAI workloads.

Releasing software shouldn't be stressful or risky. Learn how to leverage progressive delivery techniques to ensure safer deployments.

Avoid machine learning mistakes and boost model performance! Discover key ML patterns, anti-patterns, data strategies, and more.

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

  • Revolutionizing Financial Monitoring: Building a Team Dashboard With OpenObserve
  • Concourse CI/CD Pipeline: Webhook Triggers
  • Breaking Bottlenecks: Applying the Theory of Constraints to Software Development
  • Hybrid Cloud vs Multi-Cloud: Choosing the Right Strategy for AI Scalability and Security
  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 user avatar
Karthik Chintala
·
Updated Apr. 30, 19 · Tutorial
Likes (1)
Comment
Save
Tweet
Share
46.2K Views

Join the DZone community and get the full member experience.

Join For Free

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

The likes didn't load as expected. Please refresh the page and try again.

ABOUT US

  • About DZone
  • Support and feedback
  • Community research
  • Sitemap

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 100
  • Nashville, TN 37211
  • support@dzone.com

Let's be friends: