Ioana B.
Ioana B.

Reputation: 63

Add a message to your HTTP 400 Bad Request in ASP.NET Core 3.1

Is there a way I can add a message to a BadRequest action result, and for that message to be visible to external clients, such as Postman? I am using ASP.NET Core 3.1.

Part of my code is included below. I want to say what the problem is—e.g., that the id sent in the body is not the same as the one taken from the URL. For now, I am using an Error object that I’ve made, which has the error code and message. But those aren't visible in Postman when I send the request.

public ActionResult PutColour(int id, Colour colour)
{
    if (id != colour.Id)
    {
        return BadRequest(new Error("IDNotTheSame","ID from URL is not the same as in the body."));
    }
}

Upvotes: 6

Views: 15449

Answers (2)

Vikas Chaturvedi
Vikas Chaturvedi

Reputation: 507

Please follow the following steps to show Bad Request with your custom Class. Create constructor here of that class. And add manual description and many more

Step 1

Add a custom class and inherit this class with ValidationProblemDetails. After that initialize below base class constructor by passing context.ModelState.

public ValidationProblemDetails(ModelStateDictionary modelState)

Here is implementation-

public class CustomBadRequest : ValidationProblemDetails
    {
        public CustomBadRequest(ActionContext context) : base(context.ModelState)
        {
            Detail = "add details here";
            Instance = "add extension here";
            Status = 400;
            Title = "add title here";
            Type = "add type here";
        }
    }

Step 2

Add this Custom Bad request class in ConfigureServices method in Startup.cs.

public void ConfigureServices(IServiceCollection services)
        {
services.AddMvc().ConfigureApiBehaviorOptions(options =>
            {
                options.InvalidModelStateResponseFactory = context =>
                {
                    var problems = new CustomBadRequest(context);

                    return new BadRequestObjectResult(problems);
                };
            });
}

Step 3

Build and run.

and if any bad request come then you will see output like below-

enter image description here

Upvotes: 3

Chris Pratt
Chris Pratt

Reputation: 239290

What you pass to BadRequest is serialized and returned as the response body. If nothing is coming through, the only explanation is that you don't have any public properties on Error that can be serialized. For example, if you had something like:

public class Error
{
    public Error(string type, string description)
    {
        Type = type;
        Description = description;
    }

    public string Type { get; private set }
    public string Description { get; private set; }
}

Then, you get a response like:

{
    "type": "IDNotTheSame",
    "description": "ID from URL is not the same as in the body."
}

Not sure what your Error class currently does. However, this is probably unnecessary anyways, as you can just use ModelState:

ModelState.AddModelError("Id", "ID from URL is not the same as in the body.");
return BadRequest(ModelState);

Finally, it should probably be said that this is a pointless validation in the first place. You shouldn't be sending an id with the model at all (always use a view model, not an entity class), and even if you do send it, you can simply just overwrite it with the value from the URL:

model.Id = id;

Done. No issues and you don't need to worry about sending an error back.

Upvotes: 9

Related Questions