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