首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Swashbuckle.AspNetCore如何描述错误响应模型?

Swashbuckle.AspNetCore如何描述错误响应模型?
EN

Stack Overflow用户
提问于 2019-05-17 12:26:44
回答 1查看 1.8K关注 0票数 2

我有一个ASP.NET Corev2.1和Swashbuckle.AspNetCore包。

我有以下错误响应模型:

代码语言:javascript
复制
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:

代码语言:javascript
复制
        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生成适当的文档,这样,如果出现问题,客户端将知道响应的格式。

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2019-05-17 13:51:16

请看一下自述:

https://github.com/domaindrivendev/Swashbuckle.AspNetCore#explicit-responses

显式响应

如果您需要指定不同的状态代码和/或其他响应,或者您的操作返回IActionResult而不是响应DTO,则可以使用随ASP.NET Core附带的ProducesResponseTypeAttribute描述显式响应。例如..。

代码语言:javascript
复制
[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

票数 3
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/56186427

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档