首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >C# Swashbuckle

C# Swashbuckle
EN

Stack Overflow用户
提问于 2015-09-10 16:43:17
回答 1查看 3.7K关注 0票数 1

我有一个WebApi项目,我正在尝试实现Swagger。我使用的是斯瓦巴克尔(5.2.1)。在我的实际项目中,我的响应已经有了一个属性:

[ResponseForApi(HttpStatusCode.OK)]

我的问题是我正在使用Swashbuckle (5.2.1),并且我不想为我的方法添加其他属性。我知道如何将响应放到Swagger上,我可以使用“XML Comments”或以下属性:

[SwaggerResponse(HttpStatusCode.OK)]

我的问题是:有没有办法通过调用'ResponseForApi‘来使用'SwaggerResponse’?

EN

回答 1

Stack Overflow用户

发布于 2015-12-08 12:50:29

您可以通过基于ApplySwaggerResponseAttributes连接您自己的IOperationFilter来做到这一点--这是扫描SwaggerResponse的东西。下面是我基于Swashbuckle代码https://github.com/domaindrivendev/Swashbuckle/blob/master/Swashbuckle.Core/Swagger/Annotations/ApplySwaggerResponseAttributes.cs创建的代码

代码语言:javascript
复制
public class ApplyResponseTypeAttributes : IOperationFilter
{
    public void Apply(Operation operation, SchemaRegistry schemaRegistry, ApiDescription apiDescription)
    {
        if (apiDescription.GetControllerAndActionAttributes<SwaggerResponseRemoveDefaultsAttribute>().Any())
        {
            operation.responses.Clear();
        }

        // SwaggerResponseAttribute trumps ResponseTypeAttribute
        var swaggerAttributes = apiDescription.GetControllerAndActionAttributes<SwaggerResponseAttribute>();

        if (!swaggerAttributes.Any())
        {
            var responseAttributes = apiDescription.GetControllerAndActionAttributes<ResponseTypeAttribute>().OrderBy(attr => attr.ResponseType.Name);

            foreach (var attr in responseAttributes)
            {
                const string StatusCode = "200";

                operation.responses[StatusCode] = new Response
                {
                    description = InferDescriptionFrom(StatusCode),
                    schema = (attr.ResponseType != null) ? schemaRegistry.GetOrRegister(attr.ResponseType) : null
                };
            }
        }
    }

    private string InferDescriptionFrom(string statusCode)
    {
        HttpStatusCode enumValue;
        if (Enum.TryParse(statusCode, true, out enumValue))
        {
            return enumValue.ToString();
        }
        return null;
    }
}

在./App_Start中的swagger配置中,添加以下内容以注册此过滤器。实际上,在上面设置一个断点非常有趣,这样你就可以看到Swashbuckle是如何工作的,它会遍历你控制器的所有动作。

代码语言:javascript
复制
c.OperationFilter<ApplyResponseTypeAttributes>();
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/32497075

复制
相关文章

相似问题

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