首页 文章

如何使用Swashbuckle在WebAPI上省略Swagger文档中的方法

提问于
浏览
58

我有一个C#ASP.NET WebAPI应用程序,其API文档是使用Swashbuckle自动生成的 . 我希望能够从文档中得到 omit certain methods 但我似乎无法弄清楚如何告诉Swagger不要将它们包含在Swagger UI输出中 .

我觉得它与 adding a model or schema filter 有关,但它并不明显该做什么,文档似乎只提供了如何修改方法输出的示例,而不是从输出中完全删除它 .

提前致谢 .

5 回答

  • 0

    您可以将以下属性添加到控制器和操作,以从生成的文档中排除它们: [ApiExplorerSettings(IgnoreApi = true)]

  • 10

    在使用文档过滤器生成后,您可以从swagger文档中删除"operations" - 只需将动词设置为 null (但是,可能还有其他方法可以执行此操作)

    以下示例仅允许 GET 动词 - 取自this issue .

    class RemoveVerbsFilter : IDocumentFilter
    {
        public void Apply(SwaggerDocument swaggerDoc, SchemaRegistry schemaRegistry, IApiExplorer apiExplorer)
        {
            foreach (PathItem path in swaggerDoc.paths.Values)
            {
                path.delete = null;
                //path.get = null; // leaving GET in
                path.head = null;
                path.options = null;
                path.patch = null;
                path.post = null;
                path.put = null;
            }
        }
    }
    

    并在你的招摇配置:

    ...EnableSwagger(conf => 
    {
        // ...
    
        conf.DocumentFilter<RemoveVerbsFilter>();
    });
    
  • 0

    有人在github上发布了解决方案,所以我要把它粘贴到这里 . 所有学分归他所有 . https://github.com/domaindrivendev/Swashbuckle/issues/153#issuecomment-213342771

    首先创建一个Attribute类

    [AttributeUsage(AttributeTargets.Method | AttributeTargets.Class)]
    public class HideInDocsAttribute : Attribute
    {
    }
    

    然后创建一个文档过滤器类

    public class HideInDocsFilter : IDocumentFilter
    {
        public void Apply(SwaggerDocument swaggerDoc, SchemaRegistry schemaRegistry, IApiExplorer apiExplorer)
        {
            foreach (var apiDescription in apiExplorer.ApiDescriptions)
            {
                if (!apiDescription.ActionDescriptor.ControllerDescriptor.GetCustomAttributes<HideInDocsAttribute>().Any() && !apiDescription.ActionDescriptor.GetCustomAttributes<HideInDocsAttribute>().Any()) continue;
                var route = "/" + apiDescription.Route.RouteTemplate.TrimEnd('/');
                swaggerDoc.paths.Remove(route);
            }
        }
    }
    

    然后在Swagger Config类中添加该文档过滤器

    public class SwaggerConfig
    {
        public static void Register(HttpConfiguration config)
        {
            var thisAssembly = typeof(SwaggerConfig).Assembly;
    
            config
                 .EnableSwagger(c =>
                    {
                        ...                       
                        c.DocumentFilter<HideInDocsFilter>();
                        ...
                    })
                .EnableSwaggerUi(c =>
                    {
                        ...
                    });
        }
    }
    

    最后一步是在Controller或Method上添加[HideInDocsAttribute]属性,不要让Swashbuckle生成文档 .

  • 8

    我更希望完全删除路径项的字典:

    var pathsToRemove = swaggerDoc.Paths
                    .Where(pathItem => !pathItem.Key.Contains("api/"))
                    .ToList();
    
    foreach (var item in pathsToRemove)
    {
        swaggerDoc.Paths.Remove(item.Key);
    }
    

    使用这种方法,您不会在生成的swagger.json定义中获得“空”项 .

  • 131

    基于@spottedmahns answer . 我的任务反之亦然 . 仅显示允许的内容 .

    框架:.NetCore 2.1; Swagger:3.0.0

    添加了属性

    [AttributeUsage(AttributeTargets.Method | AttributeTargets.Class)]
    public class ShowInSwaggerAttribute : Attribute
    {
    }
    

    并实现自定义 IDocumentFilter

    public class ShowInSwaggerFilter : IDocumentFilter
    {
        public void Apply(SwaggerDocument swaggerDoc, DocumentFilterContext context)
        {
    
            foreach (var contextApiDescription in context.ApiDescriptions)
            {
                var actionDescriptor = (ControllerActionDescriptor) contextApiDescription.ActionDescriptor;
    
                if (actionDescriptor.ControllerTypeInfo.GetCustomAttributes<ShowInSwaggerAttribute>().Any() ||
                    actionDescriptor.MethodInfo.GetCustomAttributes<ShowInSwaggerAttribute>().Any())
                {
                    continue;
                }
                else
                {
                    var key = "/" + contextApiDescription.RelativePath.TrimEnd('/');
                    var pathItem = swaggerDoc.Paths[key];
                    if(pathItem == null)
                        continue;
    
                    switch (contextApiDescription.HttpMethod.ToUpper())
                    {
                        case "GET":
                            pathItem.Get = null;
                            break;
                        case "POST":
                            pathItem.Post = null;
                            break;
                        case "PUT":
                            pathItem.Put = null;
                            break;
                        case "DELETE":
                            pathItem.Delete = null;
                            break;
                    }
    
                    if (pathItem.Get == null  // ignore other methods
                        && pathItem.Post == null 
                        && pathItem.Put == null 
                        && pathItem.Delete == null)
                        swaggerDoc.Paths.Remove(key);
                }
            }
        }
    }
    

    ConfigureServices 代码:

    public void ConfigureServices(IServiceCollection services)
    {
         // other code
    
        services.AddSwaggerGen(c =>
        {
            // other configurations
            c.DocumentFilter<ShowInSwaggerFilter>();
        });
    }
    

相关问题