简体   繁体   English

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

[英]How to omit methods from Swagger documentation on WebAPI using Swashbuckle

I have a C# ASP.NET WebAPI application with API documentation being automatically generated using Swashbuckle .我有一个 C# ASP.NET WebAPI 应用程序,其中 API 文档是使用Swashbuckle自动生成的。 I want to be able to omit certain methods from the documentation but I can't seem to work out how to tell Swagger not to include them in the Swagger UI output.我希望能够从文档中省略某些方法,但我似乎无法弄清楚如何告诉 Swagger 不要将它们包含在 Swagger UI output 中。

I sense it is something to do with adding a model or schema filter but it isn't obvious what to do and the documentation only seems to provide examples of how to modify the output for a method, not remove it completely from the output.我感觉这与添加 model 或模式过滤器有关,但不清楚该怎么做,文档似乎只提供了如何修改方法的 output 的示例,而不是将其从 output 中完全删除。

您可以将以下属性添加到 Controllers 和 Actions 以将它们从生成的文档中排除: [ApiExplorerSettings(IgnoreApi = true)]

Someone posted the solution on github so I'm going to paste it here.有人在github上发布了解决方案,所以我将其粘贴在这里。 All credits goes to him.所有的功劳都归于他。 https://github.com/domaindrivendev/Swashbuckle/issues/153#issuecomment-213342771 https://github.com/domaindrivendev/Swashbuckle/issues/153#issuecomment-213342771

Create first an Attribute class首先创建一个 Attribute 类

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

Then create a Document Filter class然后创建一个文档过滤器类

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);
        }
    }
}

Then in Swagger Config class, add that document filter然后在 Swagger Config 类中,添加该文档过滤器

public class SwaggerConfig
{
    public static void Register(HttpConfiguration config)
    {
        var thisAssembly = typeof(SwaggerConfig).Assembly;

        config
             .EnableSwagger(c =>
                {
                    ...                       
                    c.DocumentFilter<HideInDocsFilter>();
                    ...
                })
            .EnableSwaggerUi(c =>
                {
                    ...
                });
    }
}

Last step is to add [HideInDocsAttribute] attribute on the Controller or Method you don't want Swashbuckle to generate documentation.最后一步是在您不希望 Swashbuckle 生成文档的控制器或方法上添加 [HideInDocsAttribute] 属性。

I have a C# ASP.NET WebAPI application with API documentation being automatically generated using Swashbuckle .我有一个 C# ASP.NET WebAPI 应用程序,其中使用Swashbuckle自动生成 API 文档。 I want to be able to omit certain methods from the documentation but I can't seem to work out how to tell Swagger not to include them in the Swagger UI output.我希望能够从文档中省略某些方法,但我似乎无法弄清楚如何告诉 Swagger 不要将它们包含在 Swagger UI 输出中。

I sense it is something to do with adding a model or schema filter but it isn't obvious what to do and the documentation only seems to provide examples of how to modify the output for a method, not remove it completely from the output.我觉得这与添加模型或模式过滤器有关,但不清楚该怎么做,文档似乎只提供了如何修改方法输出的示例,而不是将其从输出中完全删除。

Thanks in advance.提前致谢。

You can remove "operations" from the swagger document after it's generated with a document filter - just set the verb to null (though, there may be other ways to do it as well)您可以在使用文档过滤器生成后从 swagger 文档中删除“操作” - 只需将动词设置为null (不过,也可能有其他方法可以做到)

The following sample allows only GET verbs - and is taken from this issue .以下示例仅允许使用GET动词 - 并且取自此问题

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;
        }
    }
}

and in your swagger config:并在您的 swagger 配置中:

...EnableSwagger(conf => 
{
    // ...

    conf.DocumentFilter<RemoveVerbsFilter>();
});

May help somebody but during development (debugging) we like to expose whole Controllers and/or Actions and then hide these during production (release build)可能对某人有所帮助,但在开发(调试)期间,我们喜欢公开整个控制器和/或操作,然后在生产(发布版本)期间隐藏它们

#if DEBUG
    [ApiExplorerSettings(IgnoreApi = false)]
#else
    [ApiExplorerSettings(IgnoreApi = true)]
#endif  

I would prefer to remove the dictionary entries for path items completely:我更愿意完全删除路径项的字典条目:

var pathsToRemove = swaggerDoc.Paths
                .Where(pathItem => !pathItem.Key.Contains("api/"))
                .ToList();

foreach (var item in pathsToRemove)
{
    swaggerDoc.Paths.Remove(item.Key);
}

With this approach, you would not get "empty" items in the generated swagger.json definition.使用这种方法,您不会在生成的 swagger.json 定义中获得“空”项。

Make a filter做一个过滤器

public class SwaggerTagFilter : IDocumentFilter
{
    public void Apply(SwaggerDocument swaggerDoc, DocumentFilterContext context)
    {
        foreach(var contextApiDescription in context.ApiDescriptions)
        {
            var actionDescriptor = (ControllerActionDescriptor)contextApiDescription.ActionDescriptor;
            
            if(!actionDescriptor.ControllerTypeInfo.GetCustomAttributes<SwaggerTagAttribute>().Any() && 
               !actionDescriptor.MethodInfo.GetCustomAttributes<SwaggerTagAttribute>().Any())
            {
                var key = "/" + contextApiDescription.RelativePath.TrimEnd('/');
                swaggerDoc.Paths.Remove(key);
            }
        }
    }
}

Make an attribute做一个属性

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

Apply in startup.cs在startup.cs中申请

services.AddSwaggerGen(c => {
    c.SwaggerDoc(1, new Info { Title = "API_NAME", Version = "API_VERSION" });
    c.DocumentFilter<SwaggerTagFilter>(); // [SwaggerTag]
});

Add [SwaggerTag] attribute to methods and controllers you want to include in Swagger JSON将 [SwaggerTag] 属性添加到要包含在 Swagger JSON 中的方法和控制器

Based on @spottedmahns answer .基于@spottedmahns 的回答 My task was vice versa.我的任务是相反的。 Show only those that are allowed.仅显示允许的那些。

Frameworks: .NetCore 2.1;框架:.NetCore 2.1; Swagger: 3.0.0招摇:3.0.0

Added attribute添加属性

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

And implement custom IDocumentFilter并实现自定义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 code:配置服务代码:

public void ConfigureServices(IServiceCollection services)
{
     // other code

    services.AddSwaggerGen(c =>
    {
        // other configurations
        c.DocumentFilter<ShowInSwaggerFilter>();
    });
}

Like @aleha I wanted to exclude by default so that I didn't accidentally expose an endpoint by accident (secure by default) but was using a newer version of the Swagger that uses OpenApiDocument.像@aleha 一样,我想默认排除,这样我就不会意外地暴露端点(默认情况下是安全的),而是使用了使用 OpenApiDocument 的更新版本的 Swagger。

Create a ShowInSwagger Attribute创建 ShowInSwagger 属性

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

Then create a Document Filter然后创建一个文档过滤器

using Microsoft.AspNetCore.Mvc.Controllers;
using Microsoft.OpenApi.Models;
using Swashbuckle.AspNetCore.SwaggerGen;
using System.Reflection;
using System;
using System.Linq;
using TLS.Common.Attributes;

namespace TLS.Common.Filters
{
    public class ShowInSwaggerFilter : IDocumentFilter
    {
        public void Apply(OpenApiDocument 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 operation = (OperationType)Enum.Parse(typeof(OperationType), contextApiDescription.HttpMethod, true);

                    swaggerDoc.Paths[key].Operations.Remove(operation);

                    // drop the entire route of there are no operations left
                    if (!swaggerDoc.Paths[key].Operations.Any())
                    {
                        swaggerDoc.Paths.Remove(key);
                    }
                }
            }
        }
    }
}

then in your startup.cs or ConfigureServices:然后在您的 startup.cs 或 ConfigureServices 中:

public void ConfigureServices(IServiceCollection services)
{
     // other code

    services.AddSwaggerGen(c =>
    {
        c.DocumentFilter<ShowInSwaggerFilter>();
        // other config
    });
}

If you are using the minimal API you can use:如果您使用最小的 API,您可以使用:

app.MapGet("/hello", () => "Hello World!").ExcludeFromDescription();

Add one line to the SwaggerConfig在 SwaggerConfig 中添加一行

c.DocumentFilter<HideInDocsFilter>();

...

public class HideInDocsFilter : IDocumentFilter
{
    public void Apply(SwaggerDocument swaggerDoc, SchemaRegistry schemaRegistry, IApiExplorer apiExplorer)
    { 
        var pathsToRemove = swaggerDoc.Paths
            .Where(pathItem => !pathItem.Key.Contains("api/"))
            .ToList();
    
        foreach (var item in pathsToRemove)
        {
            swaggerDoc.Paths.Remove(item.Key);
        }
    }
}

You can create a custom filter at both Controller and Method level.您可以在控制器和方法级别创建自定义过滤器。 So any Controller/Method with your attribute will be available in the Swagger doc.因此,任何具有您的属性的控制器/方法都将在 Swagger 文档中可用。 This filter also removed the duplicate HTTP verbs from your document (in this example I make it for GET/PUT/POST/PATCH only), however, you can always customize per your requirement此过滤器还从您的文档中删除了重复的 HTTP 动词(在此示例中,我仅将其用于 GET/PUT/POST/PATCH),但是,您始终可以根据您的要求进行自定义

The attribute属性

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

}

Document filter文件过滤器

public class PublicApiFilter : IDocumentFilter
{
    public void Apply(SwaggerDocument swaggerDoc, SchemaRegistry schemaRegistry, IApiExplorer apiExplorer)
    {

        var publicPaths = new List<string> {"/api"};

        var publicApiDescriptions = new List<ApiDescription>();

        var publicMethods = FilterByPublicControllers(swaggerDoc, apiExplorer, publicPaths, publicApiDescriptions);

        FilterByPublicActions(swaggerDoc, publicApiDescriptions, publicMethods);
    }

    private static Dictionary<string, List<string>> FilterByPublicControllers(SwaggerDocument swaggerDoc, IApiExplorer apiExplorer, List<string> publicPaths, List<ApiDescription> publicApiDescriptions)
    {
        var publicMethods = new Dictionary<string, List<string>>();
        foreach (var apiDescription in apiExplorer.ApiDescriptions)
        {
            var isPublicApiController = apiDescription.ActionDescriptor.ControllerDescriptor.GetCustomAttributes<PublicApi>().Any();
            var isPublicApiMethod = apiDescription.ActionDescriptor.GetCustomAttributes<PublicApi>().Any();


            if (!isPublicApiController && !isPublicApiMethod)
            {
                continue;
            }

            var relativePath = ToRelativePath(apiDescription);

            publicPaths.Add(relativePath);
            publicApiDescriptions.Add(apiDescription);

            var action = apiDescription.ActionDescriptor.ActionName;
            List<string> available = null;
            if (!publicMethods.TryGetValue(relativePath, out available))
                publicMethods[relativePath] = new List<string>();
            publicMethods[relativePath].Add(action);
        }

        swaggerDoc.paths = swaggerDoc.paths.Where(pair => publicPaths.Contains(pair.Key))
            .ToDictionary(pair => pair.Key,
                pair => pair.Value);
        return publicMethods;
    }

    private static void FilterByPublicActions(SwaggerDocument swaggerDoc, List<ApiDescription> publicApis, Dictionary<string, List<string>> publicMethods)
    {
        foreach (var api in publicApis)
        {
            var relativePath = ToRelativePath(api);
            var availableActions = publicMethods[relativePath];
            if (availableActions == null)
            {
                continue;
            }

            foreach (var path in swaggerDoc.paths.Where(pair => pair.Key.IndexOf(relativePath) > -1).ToList())
            {
                if (!availableActions.Contains("Get"))
                    path.Value.get = null;
                if (!availableActions.Contains("Post"))
                    path.Value.post = null;
                if (!availableActions.Contains("Put"))
                    path.Value.put = null;
                if (!availableActions.Contains("Patch"))
                    path.Value.patch = null;
            }
        }
    }

    private static string ToRelativePath(ApiDescription apiDescription)
    {
        return "/" + apiDescription.RelativePath.Substring(0,apiDescription.RelativePath.LastIndexOf('/'));
    }
}

And finally, register your SwaggerConfig最后,注册您的 SwaggerConfig

public class SwaggerConfig
{
    public static void Register()
    {

        var thisAssembly = typeof(SwaggerConfig).Assembly;
        GlobalConfiguration.Configuration
            .EnableSwagger(c =>
                {
                    c.SingleApiVersion("v1", "Reports");
                    c.ResolveConflictingActions(apiDescriptions => apiDescriptions.First());
                    c.DocumentFilter<PublicApiFilter>();
                })
            .EnableSwaggerUi(c =>
                {

                });

    }
}

Examples例子

Controller控制器

[PublicApi]
public class ProfileController : ApiController

Method方法

 public class UserController : ApiController
 {
    [PublicApi]
    public ResUsers Get(string sessionKey, int userId, int groupId) {
        return Get(sessionKey, userId, groupId, 0);
    }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 使用 Swashbuckle / Swagger 的 C# 版本化 WebApi 文档 - C# versioned WebApi documentation using Swashbuckle / Swagger 使用swashbuckle在swagger文档中显示[Route]中的名称 - Show Name from [Route] in swagger documentation using swashbuckle 如何使用swagger swashbuckle保护生成的API文档 - How to secure generated API documentation using swagger swashbuckle 用于 Swagger 文档的 UsePathBase 和 Swashbuckle - UsePathBase and Swashbuckle for Swagger Documentation 如何使用 Swashbuckle 在 Swagger API 文档/OpenAPI 规范中包含子类? - How do I include subclasses in Swagger API documentation/ OpenAPI specification using Swashbuckle? Swashbuckle - 返回响应的大摇大摆的文档? - Swashbuckle - swagger documentation of returned response? Swagger Swashbuckle 抽象类文档 - Swagger Swashbuckle abstract class documentation 如何在swagger / swashbuckle WebAPI 2中定义响应错误元数据 - How to define response error metadata in swagger/swashbuckle WebAPI 2 使用ASP.NET MVC WebApi的Swashbuckle 5.4.0 - 在swagger网页中没有显示任何文档 - Swashbuckle 5.4.0 with ASP.NET MVC WebApi - No documentation is shown inside the swagger webpage 如何从 Swagger 文档方法中删除 Controller 名称 - How to remove the Controller Name from Swagger Documentation methods
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM