[英]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.我的 ASP.NET Core 3.1 应用程序中有一个 controller 在其中一种情况下返回BadRequest()
。 By default it produces the json response:默认情况下,它会产生 json 响应:
{
"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.这太棒了,但我想添加一个带有特定消息的detail
字符串值。
When I return BadRequest("msg")
, the response is a plain text msg
.当我返回BadRequest("msg")
时,响应是纯文本msg
。
When I do it this way BadRequest(new { Detail = "msg" })
, the response is a json:当我这样做BadRequest(new { Detail = "msg" })
时,响应是 json:
{
"detail": "msg"
}
Which is better, but I'd like to preserve the original json data as well.哪个更好,但我也想保留原始的 json 数据。
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. ControllerBase.Problem方法非常适合这种情况。 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:为了完整起见,这里是 output 的示例:
{
"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.在输入的 object 中获取 Json 数据并将此响应发回。
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.使用此 class 类型转换您的 Json 数据并在detail
信息字段中添加详细信息。
var obj = JsonConvert.DeserializeObject<MyClass>(yourJson);
obj.detail = "msg";
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.