简体   繁体   中英

Opt-In routes in Swashbuckle

I have realized a relatively large MVC project with asp core 3.0. Now I want to add an API under the /api/* endpoint and use swashbuckle to provide documentation.

How is it possible that only routes starting with /api appear in the documentation?

The use of [ApiExplorerSettings(IgnoreApi = true)] in all the other controllers I want to avoid.

Is there an alternative possibility to include only certain controllers in the documentation, so to speak an Opt-In?

The ApiExplorerSettings attribute is the recommended one. You can also use the following code.

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

And the document filter can be applied like this.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM