英文:
How to return a full BadRequest response body with my own error
问题
Good day
我是新手对API的理解。 我已经使用过它们,但直到现在才不得不发布自己的API。
我想要在所有错误响应中保持统一性。 除了200范围之外的所有响应都应该与默认错误响应看起来一样,但当我添加自己的错误时,Postman中只返回我的错误。
说明:
例如,当未传递所需参数时,会有一个自动默认的响应体,看起来像这样:
{
"type": "https://tools.ietf.org/html/rfc7231#section-6.5.1",
"title": "One or more validation errors occurred.",
"status": 400,
"traceId": "00-118adfb731bbdb32e865873f70487da2-f5994dea1e69866a-00",
"errors": {
"Spec": [
"The Spec field is required."
]
}
}
请注意,我没有验证字段,也没有生成上述错误消息。
当我返回BadRequest()响应时,在Postman中我看到一个响应体,其中还包含类型、状态、标题和traceId:
API:
public async Task<IActionResult> GetList([FromQuery] SearchCriteria criteria)
{
return BadRequest();
}
响应:
{
"type": "https://tools.ietf.org/html/rfc7231#section-6.5.1",
"title": "Bad Request",
"status": 400,
"traceId":
}
但是,当我添加错误消息时,Postman中只返回我的错误消息:
API:
public async Task<IActionResult> GetList([FromQuery] SearchCriteria criteria)
{
return BadRequest(error: new { error = "Unable to return list" });
}
响应:
{
"error": "Unable to return list"
}
我如何添加自己的错误消息,同时仍然在响应中包含类型、标题、状态和traceId,以便用户始终知道可以期望什么?
非常感谢。
英文:
Good day
I am new to API's. I have consumed them, but never had to published my own until now.
I would like to have uniformity in all error responses. I would like to have all my responses (other than 200 range) look the same as the default error response, but when I add my own error, then only my error is returned in Postman.
Illustration:
When a required parameter is not passed for example, there is an auto default response body which look like this:
{
"type": "https://tools.ietf.org/html/rfc7231#section-6.5.1",
"title": "One or more validation errors occurred.",
"status": 400,
"traceId": "00-118adfb731bbdb32e865873f70487da2-f5994dea1e69866a-00",
"errors": {
"Spec": [
"The Spec field is required."
]
}
}
Note that I am not validating fields and I did not generate the above error message.
When I return a BadRequest() response, in Postman I see a response body also containing the type, status, title and traceId:
API:
public async Task<ActionResult> GetList([FromQuery] SearchCriteria criteria)
{
return BadRequest();
}
Response:
{
"type": "https://tools.ietf.org/html/rfc7231#section-6.5.1",
"title": "Bad Request",
"status": 400,
"traceId":
}
BUT when I add an error message, then only my error message is returned in Postman:
API:
public async Task<ActionResult> GetList([FromQuery] SearchCriteria criteria)
{
return BadRequest(error: new { error = "Unable to return list" });
}
Response:
{
"error": "Unable to return list"
}
How can I add my own error message and also still have the type, title, status, and traceId in the response so the user always knows what to expect?
Thank you in advance.
答案1
得分: 2
The translated code part:
可能最简单的方法是使用 `ValidationProblem`:
ModelState.AddModelError("return", "无法返回列表");
return ValidationProblem(ModelState);
And the JSON response:
{
"type":"https://tools.ietf.org/html/rfc7231#section-6.5.1",
"title":"发生一个或多个验证错误。",
"status":400,
"traceId":"00-4091c0b6419e8cc5d4e9cb1da3764f11-d2bc593ce1a51e0a-00",
"errors":{
"return":[
"无法返回列表"
]
}
}
The link remains the same.
英文:
Probably easiest approach would be using ValidationProblem
:
ModelState.AddModelError("return", "Unable to return List");
return ValidationProblem(ModelState);
Which produces the following response for me:
{
"type":"https://tools.ietf.org/html/rfc7231#section-6.5.1",
"title":"One or more validation errors occurred.",
"status":400,
"traceId":"00-4091c0b6419e8cc5d4e9cb1da3764f11-d2bc593ce1a51e0a-00",
"errors":{
"return":[
"Unable to return List"
]
}
}
Otherwise you might need to dabble with methods exposed by ProblemDetailsFactory
.
答案2
得分: 0
JsonResult
应返回一个自定义类
JsonResult
具有一个可设置的StatusCode
属性
// 返回到客户端的模型
private class ReturnModel
{
public string? message { get; set; }
...
}
// 在控制器方法中
return new JsonResult(new ReturnModel
{
message = "..."
})
{
StatusCode = (int)HttpStatusCode.BadRequest
};
英文:
You should return a JsonResult
with a custom class
JsonResult
has a StatusCode
property you can set
// model to return to client side
private class ReturnModel
{
public string? message { get; set; }
...
}
// in controller method
return new JsonResult(new ReturnModel
{
message = "..."
})
{
StatusCode = (int)HttpStatusCode.BadRequest
};
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论