How to omit methods from Swagger documentation on WebAPI using Swashbuckle

前端 未结 10 883
不思量自难忘°
不思量自难忘° 2020-11-30 19:38

I have a C# ASP.NET WebAPI application with API documentation being automatically generated using Swashbuckle. I want to be able to omit certain methods fr

10条回答
  •  离开以前
    2020-11-30 20:28

    Someone posted the solution on github so I'm going to paste it here. All credits goes to him. https://github.com/domaindrivendev/Swashbuckle/issues/153#issuecomment-213342771

    Create first an Attribute class

    [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().Any() && !apiDescription.ActionDescriptor.GetCustomAttributes().Any()) continue;
                var route = "/" + apiDescription.Route.RouteTemplate.TrimEnd('/');
                swaggerDoc.paths.Remove(route);
            }
        }
    }
    

    Then in Swagger Config class, add that document filter

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

    Last step is to add [HideInDocsAttribute] attribute on the Controller or Method you don't want Swashbuckle to generate documentation.

提交回复
热议问题