How to omit methods from Swagger documentation on WebAPI using Swashbuckle

前端 未结 10 939
不思量自难忘°
不思量自难忘° 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:13

    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().Any() && 
        !actionDescriptor.MethodInfo.GetCustomAttributes().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

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

    Add [SwaggerTag] attribute to methods and controllers you want to include in Swagger JSON

提交回复
热议问题