5

I have a controller in my ASP.NET Core 3.1 app that returns BadRequest() in one of the cases. By default it produces the json response:

{
  "type": "https://tools.ietf.org/html/rfc7231#section-6.5.1",
  "title": "Bad Request",
  "status": 400,
  "traceId": "|492dbc28-4cf485d536d40917."
}

Which is awesome, but I'd like to add a detail string value with a specific message.

When I return BadRequest("msg"), the response is a plain text msg.

When I do it this way BadRequest(new { Detail = "msg" }), the response is a json:

{
  "detail": "msg"
}

Which is better, but I'd like to preserve the original json data as well.

My goal is to return this kind of response:

{
  "type": "https://tools.ietf.org/html/rfc7231#section-6.5.1",
  "title": "Bad Request",
  "detail": "msg",
  "status": 400,
  "traceId": "|492dbc28-4cf485d536d40917."
}

Is there a way to accomplish this?

2 Answers2

13

The ControllerBase.Problem method is a perfect fit for this. Here's an example that produces the desired response:

public IActionResult Post()
{
    // ...

    return Problem("msg", statusCode: (int)HttpStatusCode.BadRequest);
}

Here's an example of the output, for completeness:

{
  "type": "https://tools.ietf.org/html/rfc7231#section-6.5.1",
  "title": "Bad Request",
  "status": 400,
  "detail": "msg",
  "traceId": "|670244a-4707fe3038da8462."
}
Kirk Larkin
  • 84,915
  • 16
  • 214
  • 203
0

Get the Json data in typed object and send this response back.

class MyClass
{
    public string type { get; set; }
    public string title { get; set; }
    public string status { get; set; }
    public string traceId { get; set; }
    public string detail { get; set; }
}

Convert your Json data with this class Type and add the detail message in detail field.

var obj = JsonConvert.DeserializeObject<MyClass>(yourJson);
obj.detail = "msg";
Sh.Imran
  • 1,035
  • 7
  • 13