简体   繁体   中英

Add detail message to ASP.NET Core 3.1 standard JSON BadRequest response

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?

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."
}

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";

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM