asp.net-core - Swashbuckle.AspNetCore 如何描述错误响应模型?
问题描述
我有一个带有Swashbuckle.AspNetCore
包的 ASP.NET Core v2.1。
我有以下错误响应模型:
public class ErrorResponse
{
[JsonProperty(PropertyName = "error")]
public Error Error { get; set; }
}
public class Error
{
[JsonProperty(PropertyName = "code")]
public string Code { get; set; }
[JsonProperty(PropertyName = "message")]
public string Message { get; set; }
[JsonProperty(PropertyName = "target")]
public string Target { get; set; }
[JsonProperty(PropertyName = "details")]
public List<ErrorDetail> Details { get; set; }
[JsonProperty(PropertyName = "innererror")]
public InnerError InnerError { get; set; }
}
public class ErrorDetail
{
[JsonProperty(PropertyName = "code")]
public string Code { get; set; }
[JsonProperty(PropertyName = "message")]
public string Message { get; set; }
[JsonProperty(PropertyName = "target")]
public string Target { get; set; }
}
public class InnerError
{
[JsonProperty(PropertyName = "code")]
public string Code { get; set; }
[JsonProperty(PropertyName = "innererror")]
public InnerError NestedInnerError { get; set; }
}
因此,例如,如果出现问题,我的 API 端点会返回ErrorResponse
具有适当 StatusCode 类型的对象:
if (String.IsNullOrWhiteSpace(token))
{
ErrorResponse errorResponse = new ErrorResponse() { Error = new Error() };
errorResponse.Error.Code = "InvalidToken";
errorResponse.Error.Target = "token";
errorResponse.Error.Message = "Token is not specified";
return new BadRequestObjectResult(errorResponse);
}
我如何使用生成适当的文档Swashbuckle.AspNetCore
,因此,如果出现问题,客户将知道响应格式?
解决方案
看一下自述文件:
https ://github.com/domaindrivendev/Swashbuckle.AspNetCore#explicit-responses
显式响应
如果您需要指定不同的状态代码和/或其他响应,或者您的操作返回 IActionResult 而不是响应 DTO,您可以使用 ASP.NET Core 附带的 ProducesResponseTypeAttribute 来描述显式响应。例如 ...
[HttpPost("{id}")]
[ProducesResponseType(typeof(Product), 200)]
[ProducesResponseType(typeof(IDictionary<string, string>), 400)]
[ProducesResponseType(500)]
public IActionResult GetById(int id)
因此,在您的情况下,您应该添加:
[ProducesResponseType(typeof(ErrorResponse), 400)]
对于那些返回错误的操作,这里有一些很好的阅读:
https ://docs.microsoft.com/en-us/aspnet/core/web-api/advanced/conventions
推荐阅读
- kubernetes - 如果 Kubernetes 没有内置负载均衡器,怎么会命中不同的 pod?
- android - findViewById(R.id.videoView) 在片段中返回 Null (Android Studio)
- python - 从 VC++ 延迟加载 Python3 dll
- javascript - 推送到在回调中不起作用的数组
- unity3d - 对象生成差距
- yelp-fusion-api - 当 Yelp Business Search 偏移 + 限制大于 240 时出现 500 错误
- ios - 如何使用 .crt 和 .key 文件快速发送 https 请求
- python - connection.commit() 和 cursor.execute('commit') 有什么区别?
- gitlab - 无法在 Gitlab Wiki 中使用 img 标签从 Google 存储中插入经过身份验证的 URL 的图像
- javascript - 将数组和对象添加到数组反应钩子