C# .NET Enable Swagger UI only for specific api controller or for api controllers within module (project)

Viewed 1004

Is there any way to configure Swagger so that it generates UI & documentation only for a certain API controller within solution, or for a group of API controllers that belong to specific module (project withing solution)?

My solution consist of 50+ projects, several of them contains many API controllers, but I need to enable Swagger only for one of them, located in specific project.

I know about [ApiExplorerSettings(IgnoreApi = true)] attribute, but this way I would need to set this attribute to all API controllers which I don't need, and I would like just to mark the specific API controller which I want to use swagger on.

Is there any way to do that?

1 Answers

You can use conventions for this when registering your controllers.

If you create a new IActionModelConvention, something like this:

public class WhitelistControllersConvention : IActionModelConvention
{
    public void Apply(ActionModel action)
    {
        if (action.Controller.ControllerName == "Item")
        {
            action.ApiExplorer.IsVisible = true;
        }
        else
        {
            action.ApiExplorer.IsVisible = false;
        }
    }
}

Then use it when configuring swagger in Startup:

services.AddControllers(c =>
{
    c.Conventions.Add(new WhitelistControllersConvention());
});

Then you can control which controllers get included. In my example I'm just doing it off the name (only including ItemController), but you can change that to identify the controllers that you want however you want to do it.

Related