3

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."));
    }
}
Jeremy Caney
  • 7,102
  • 69
  • 48
  • 77
Ioana B.
  • 33
  • 1
  • 5

2 Answers2

7

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.

Chris Pratt
  • 232,153
  • 36
  • 385
  • 444
  • Thank you a lot! Yes, the problem was that in my Error class I had attributes, not properties. Also, thanks for the extra information, very helpful. I will check the internet to see more about view models, but I understood the idea you wrote me – Ioana B. Apr 19 '20 at 19:24
  • And I also want to say thank you to Jeremy Caney, who made the question more correct :) Don't know if this is the right place, but hey, I tried :) – Ioana B. Apr 19 '20 at 19:27
2

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

  • This should be voted up to my mind as this uses **Problem Details** as specified in [RFC 7807](https://datatracker.ietf.org/doc/html/rfc7807). One should always try to use standards where there's no explicit reason not to as to make using/ understanding APIs easier for all of us. Error handling with Problem Details is also described in the Microsoft Docs for ASP.NET Core. Please see [Produce a Problem Details Payload](https://learn.microsoft.com/en-us/aspnet/core/web-api/handle-errors?view=aspnetcore-6.0#produce-a-problemdetails-payload-for-exceptions) – Mushroomator Jul 08 '22 at 10:53