R.Haughton
R.Haughton

Reputation: 337

Swashbuckle Swagger for modular monoliths

I'm migration my monolith to a modular monolith.

I would like to have 1 definition by module.

I followed this blog to achieve the modular monolith architecture. https://www.thinktecture.com/en/asp-net-core/modular-monolith/

My problem is that my swagger is by default grouping all my endpoints by controllers.

I would like to be able to select a definition by module (option at the top of swagger) enter image description here

Select a definition: Module1, Module2

My endpoints from module1 would only be visible when I select the module1 definitions.

Is there a way to achieve that?

if this helps here is my routing for modules: [Route("api/[module]/[controller]")]

I use this RoutingConvention

public class ModuleRoutingConvention : IActionModelConvention
{
    private readonly IEnumerable<Module> _modules;

    public ModuleRoutingConvention(IEnumerable<Module> modules)
    {
        _modules = modules;
    }

    public void Apply(ActionModel action)
    {
        var module = _modules.FirstOrDefault(m => m.Assembly == action.Controller.ControllerType.Assembly);
        if (module == null)
        {
            return;
        }

        action.RouteValues.Add("module", module.RoutePrefix);
    }
}

Upvotes: 1

Views: 311

Answers (1)

Qing Guo
Qing Guo

Reputation: 9132

My endpoints from module1 would only be visible when I select the module1 definitions.

Do you want split different controllers to different Swagger definitions ?

Below is work demo, hope it can help.

In Program.cs (asp.net core 6.0+) add below code:

   builder.Services.AddSwaggerGen(d =>
    {
        d.SwaggerDoc("main", new OpenApiInfo
        {
            Title = "Main",
            Version = "v1",
            Description = "The main information",
            Contact = new OpenApiContact
            {
                Name = "itsfinniii"
            }
        });
    
        d.SwaggerDoc("sub", new OpenApiInfo
        {
            Title = "Sub",
            Version = "v1",
            Description = "Sub stuff",
            Contact = new OpenApiContact
            {
                Name = "itsfinniii"
            }
        });
    });
    ...
   app.UseSwaggerUI(c =>
    {
        c.SwaggerEndpoint("/swagger/main/swagger.json", "main");
        c.SwaggerEndpoint("/swagger/sub/swagger.json", "sub");
    });

Then add [ApiExplorerSettings(GroupName = "main")] and [ApiExplorerSettings(GroupName = "sub")] before your controller.

result:

enter image description here

You can read Swashbuckle.AspNetCore to know more.

Upvotes: 0

Related Questions