Swashbuckle通用响应代码

时间:2018-07-12 18:20:48

标签: asp.net-core-mvc swagger swashbuckle

是否可以通过某种方式定义适用于所有呼叫的“通用”响应代码。

例如,所有呼叫均可返回以下之一:

400 - Bad request
500 - Internal server error (unknown exception occurred)
503 - Service unavailable (maintenance mode)

如果我可以在某个中心位置进行定义,那么与其在每个端点上复制粘贴注释和属性,不如这么做。

2 个答案:

答案 0 :(得分:2)

感谢@HelderSepu确实是IDocumentFilter是解决方案

// Swagger config
swagger.DocumentFilter<DefaultFilter>();

internal class DefaultFilter : IDocumentFilter
{
    public void Apply(SwaggerDocument swaggerDoc, DocumentFilterContext context)
    {
        foreach (var item in swaggerDoc.Paths.Values)
        {
            UpdateItem(item, "400", "Bad or malformed request.");
            UpdateItem(item, "500", "Internal server error.");
            UpdateItem(item, "503", "Service in maintenance mode.");
        }
    }

    private static void UpdateItem(PathItem item, string key, string description)
    {
        TrySetValue(item.Get, key, description);
        TrySetValue(item.Put, key, description);
    }

    private static void TrySetValue(Operation op, string key, string description)
    {
        if ( (op == null) || (op.Responses.ContainsKey(key)) )
        {
            return;
        }

        op.Responses.Add(key, new Response
        {
            Description = description,
        });
    }
}

答案 1 :(得分:0)

对于使用Swashbuckle 5的任何人

//in AddSwaggerGen
c.OperationFilter<GeneralExceptionOperationFilter>();
internal class GeneralExceptionOperationFilter : IOperationFilter
{
    public void Apply(OpenApiOperation operation, OperationFilterContext context)
    {
        operation.Responses.Add("401", new OpenApiResponse() { Description = "Unauthorized" });
        operation.Responses.Add("403", new OpenApiResponse() { Description = "Forbidden" });

        //Example where we filter on specific HttpMethod and define the return model
        var method = context.MethodInfo.GetCustomAttributes(true)
            .OfType<HttpMethodAttribute>()
            .Single();

        if (method is HttpDeleteAttribute || method is HttpPostAttribute || method is HttpPatchAttribute || method is HttpPutAttribute)
        {
            operation.Responses.Add("409", new OpenApiResponse()
            {
                Description = "Conflict",
                Content = new Dictionary<string, OpenApiMediaType>()
                {
                    ["application/json"] = new OpenApiMediaType
                    {
                        Schema = context.SchemaGenerator.GenerateSchema(typeof(string), context.SchemaRepository)
                    }
                }
            });
        }
    }
}