我有一个带有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
生成适当的文档,因此,如果出现问题,客户端将知道响应格式?
答案 0 :(得分:1)
看看自述文件:
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