[英]How to return BadRequest response with custom error model? WEB API 2
我想用 BadRequest 返回 json 以下
{
"error": {
"code": "BAD_REQUEST_ERROR",
"description": "frId is/are not required and should not be sent",
"source": null,
"step": null,
"reason": null,
"metadata": {}
}
}
您可以制作一個 class 來封裝響應 object ,如下所示:
class Error
{
public string Code { get; set; }
public string Description { get; set; }
public string Source { get; set; }
public string Step { get; set; }
public string Reason { get; set; }
public object Metadata { get; set; }
}
然后您可以像這樣返回該 object 的實例:
[HttpGet]
public IActionResult SomeGetReq()
{
try
{
return Ok(someService.SomeMethod());
}
catch (Exception e)
{
// you can use e here
return BadRequest(new Error
{
Code = "BAD_REQUEST_ERROR",
Description = "frId is/are not required and should not be sent"
});
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.