Swashbuckle一般响应代码

问题描述 投票:0回答:2

是否有某种方法来定义适用于所有呼叫的'通用'响应代码。

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

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

而不是将注释和属性复制粘贴到每个端点上,如果我可以在某个中心位置进行定义,那就太好了。

asp.net-core-mvc swagger swashbuckle
2个回答
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,
        });
    }
}

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)
                    }
                }
            });
        }
    }
}
© www.soinside.com 2019 - 2024. All rights reserved.