ABP.IO WEB應用程式框架 Swagger 隱藏指定 API

筆記一下 Swagger DocumentFilter 用法

首先新增一個 Filter 繼承 IDocumentFilter

public class HideIdentityUserFilter : IDocumentFilter
{
    private const string pathToHide = "/api/identity/users";

    public void Apply(OpenApiDocument swaggerDoc, DocumentFilterContext context)
    {
        var identityUserPaths = swaggerDoc
            .Paths
            .Where(pathItem => pathItem.Key.Contains(pathToHide, StringComparison.OrdinalIgnoreCase))
            .ToList();

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

然後加到 ConfigureServices

services.AddAbpSwaggerGen(
    options =>
    {
        options.SwaggerDoc("v1", new OpenApiInfo {Title = "PlmAPI API", Version = "v1"});
        options.DocInclusionPredicate((docName, description) => true);
        options.CustomSchemaIds(type => type.FullName);
        // add filter
        options.DocumentFilter<HideIdentityUserFilter>();
    }
);

當然 Filter 裡頭的 path 需要改成自己要隱藏的 api 路徑 (就 swagger 畫面顯示的網址)

參照:How to hide an endpoint from Swagger? #264 | Support Center | ABP Commercial

PS5