Swashbuckle 中的选择加入路线

Opt-In routes in Swashbuckle

我用asp core 3.0实现了一个比较大的MVC项目。 现在我想在 /api/* 端点下添加一个 API 并使用 swashbuckle 提供文档。

文档中怎么可能只出现以/api开头的路由?

我想避免在所有其他控制器中使用 [ApiExplorerSettings(IgnoreApi = true)]

是否有另一种可能性,即在文档中仅包含某些控制器,可以说是选择加入?

ApiExplorerSettings 属性是推荐的属性。您也可以使用以下代码。

public class ExcludeControllersFilter : IDocumentFilter
{
    public void Apply(OpenApiDocument swaggerDoc, DocumentFilterContext context)
    {
        var pathsToRemove = swaggerDoc.Paths
            .Where(pathItem => !pathItem.Key.Contains("api/"))
            .ToList();

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

并且可以像这样应用文档过滤器。

services.ConfigureSwaggerGen(options =>
{
    options.DocumentFilter<ExcludeControllersFilter>();
});