首页 > 解决方案 > 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,因此,如果出现问题,客户将知道响应格式?

标签: asp.net-coreswaggerdocumentationswashbuckle

解决方案


看一下自述文件:
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


推荐阅读