[英]How to return BadRequest response with custom error model? WEB API 2
I want to return below json with BadRequest我想用 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": {}
}
}
You can make a class to encapsulate the response object like this:您可以制作一个 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; }
}
Then you can return a instance of that object like this:然后您可以像这样返回该 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.