Remove RavenDb’s API from Swagger

I’ve been working on a small IoT project where we expose a simple REST API and use RavenDB Embedded as the database. Once we enabled Swagger on our project we noticed that the generated documentation was not only showing our API but those exposed by RavenDB too. So the question came up: how can we Remove RavenDb’s API from Swagger Documentation?

Turns out that Swashbuckle.Swagger let’s you create your own Document Filters implementing the IDocumentFilter interface.

Below you’ll find the fast solution I came up with, and it’s easy to modify if you need to remove any other type from your Swagger documentation.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
    using Swashbuckle.Swagger;
    using System.Collections.Generic;
    using System.Linq;
    using System.Web.Http.Description;
 
    public class HideRavenDocumentFilter : IDocumentFilter
    {
        public void Apply(SwaggerDocument swaggerDoc, SchemaRegistry schemaRegistry, IApiExplorer apiExplorer)
        {
            foreach (var apiDescription in apiExplorer.ApiDescriptions)
            {
                if (!apiDescription.ActionDescriptor.ControllerDescriptor.ControllerType.Namespace.StartsWith("Raven"))
                {
                    continue;
                }
 
                var routeToRemove = swaggerDoc.paths.Where(r => r.Key.Contains(apiDescription.ActionDescriptor.ControllerDescriptor.ControllerName))
                    .FirstOrDefault();
 
                if (!routeToRemove.Equals(default(KeyValuePair<string, PathItem>)))
                {
                    swaggerDoc.paths.Remove(routeToRemove);
                }
            }
        }
    }

Hope it helps!

Leave a Reply