【问题标题】:Automatically generate default 200 OK response while specifying other response types在指定其他响应类型时自动生成默认的 200 OK 响应
【发布时间】:2017-07-18 15:00:43
【问题描述】:

根据#216,Swashbuckle 将自动生成 200 成功响应作为默认行为,否则期望指定所有响应类型。

我希望能够向 XML cmets 中的某些端点添加 404/400 错误响应,同时为所有端点保留 200 个成功响应,包括具有 404/400 错误响应的端点。

即使指定了错误响应,是否可以让 Swashbuckle 继续为所有端点自动生成 200 成功响应?

编辑:我添加了一个操作过滤器以编程方式添加缺少的 200 个响应,这解决了缺少的模型模式,但仍然没有真正回答我最初的问题,即是否有办法保持 Swashbuckle 自动生成 200 个成功响应

class CustomOperationFilter : IOperationFilter
{
    public void Apply(Operation operation, SchemaRegistry schemaRegistry, ApiDescription apiDescription)
    {
        var responses = operation.responses;
        if (responses.ContainsKey("404") || responses.ContainsKey("400"))
        {
            responses.Add("200", new Response()
            {
                description = "OK",
                schema = (schemaRegistry.GetOrRegister(apiDescription.ActionDescriptor.ReturnType))
            });
        }
    }
}

【问题讨论】:

  • 可能不是没有在 Swashbuckle 本身中闲逛。对于它的价值,您的解决方案非常方便,您应该考虑将其发布为自我回答/解决方法。也许更一般地只是检查响应不包含键“200”?
  • 谢谢!只需更改检查以查看响应是否不包含键“200”。在添加 200 响应以避免异常之前,我必须添加一个额外的检查以确保 ReturnType 不为空,因为某些端点(如删除)根本不返回任何内容

标签: c# api swagger swashbuckle


【解决方案1】:

以下是向具有指定错误响应的端点添加缺少的 200 个成功响应的解决方法:

class CustomOperationFilter : IOperationFilter
{
    public void Apply(Operation operation, SchemaRegistry schemaRegistry, ApiDescription apiDescription)
    {
        var responses = operation.responses;
        if (!responses.ContainsKey("200"))
        {
            if (apiDescription.ActionDescriptor.ReturnType != null)
            {
                responses.Add("200", new Response()
                {
                    description = "OK",
                    schema = (schemaRegistry.GetOrRegister(apiDescription.ActionDescriptor.ReturnType))
                });
            }
        }
    }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-05-24
    • 2020-01-30
    • 1970-01-01
    相关资源
    最近更新 更多