我有一个c# ASP。使用Swashbuckle自动生成带有API文档的NET WebAPI应用程序。我想能够从文档中省略某些方法,但我似乎不知道如何告诉Swagger不包括他们在Swagger UI输出。

我觉得这与添加模型或模式过滤器有关,但不清楚要做什么,文档似乎只提供了如何修改方法输出的示例,而不是完全从输出中删除它。


当前回答

制作一个滤镜

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

创建一个属性

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

在startup.cs中申请

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

为你想包含在Swagger JSON中的方法和控制器添加[SwaggerTag]属性

其他回答

在swagger文档使用文档过滤器生成后,您可以从该文档中删除“operations”—只需将谓词设置为null(不过,也可能有其他方法可以做到这一点)

下面的示例只允许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;
        }
    }
}

在你狂妄自大的装扮中:

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

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

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

你可以向控制器和动作添加以下属性,以将它们从生成的文档中排除:

如果你正在使用最小的API,你可以使用:

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

可能会帮助某些人,但在开发(调试)期间,我们喜欢暴露整个控制器和/或动作,然后在生产(发布构建)期间隐藏它们

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