我有一个ASP.NET Corev2.1和Swashbuckle.AspNetCore包。
我有以下错误响应模型:
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生成适当的文档,这样,如果出现问题,客户端将知道响应的格式。
发布于 2019-05-17 13:51:16
请看一下自述:
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://learn.microsoft.com/en-us/aspnet/core/web-api/advanced/conventions
https://stackoverflow.com/questions/56186427
复制相似问题