![](/img/trans.png)
[英]Overriding BadRequest response in ASP.NET Core ResourceFilter
[英]Add detail message to ASP.NET Core 3.1 standard JSON BadRequest response
我的 ASP.NET Core 3.1 應用程序中有一個 controller 在其中一種情況下返回BadRequest()
。 默認情況下,它會產生 json 響應:
{
"type": "https://tools.ietf.org/html/rfc7231#section-6.5.1",
"title": "Bad Request",
"status": 400,
"traceId": "|492dbc28-4cf485d536d40917."
}
這太棒了,但我想添加一個帶有特定消息的detail
字符串值。
當我返回BadRequest("msg")
時,響應是純文本msg
。
當我這樣做BadRequest(new { Detail = "msg" })
時,響應是 json:
{
"detail": "msg"
}
哪個更好,但我也想保留原始的 json 數據。
我的目標是返回這種響應:
{
"type": "https://tools.ietf.org/html/rfc7231#section-6.5.1",
"title": "Bad Request",
"detail": "msg",
"status": 400,
"traceId": "|492dbc28-4cf485d536d40917."
}
有沒有辦法做到這一點?
ControllerBase.Problem方法非常適合這種情況。 這是一個產生所需響應的示例:
public IActionResult Post()
{
// ...
return Problem("msg", statusCode: (int)HttpStatusCode.BadRequest);
}
為了完整起見,這里是 output 的示例:
{
"type": "https://tools.ietf.org/html/rfc7231#section-6.5.1",
"title": "Bad Request",
"status": 400,
"detail": "msg",
"traceId": "|670244a-4707fe3038da8462."
}
在輸入的 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; }
}
使用此 class 類型轉換您的 Json 數據並在detail
信息字段中添加詳細信息。
var obj = JsonConvert.DeserializeObject<MyClass>(yourJson);
obj.detail = "msg";
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.