Swagger Grouping With Controller Name Fallback Using Swashbuckle.AspNetCore

Written by Ken Dale

We’ve been using Swagger via Swashbuckle for some time with our ASP.NET Full Framework applications. As we’re moving toward ASP.NET Core we encountered some difficulty in achieving the same grouping behavior with ASP.NET Core using Swashbuckle.AspNetCore as we had with ASP.NET Full Framework.

Since [ResourceGroup("Custom Group Name")] is no longer applicable we can use [ApiExplorerSettings(GroupName = "Custom Group Name")], along with the following code that includes a fallback when the GroupName is not explicitly set:


Add this to ConfigureServices in your ASP.NET Core Startup class:

services.AddSwaggerGen(c =>
    c.SwaggerDoc("v1", new OpenApiInfo { Title = "API", Version = "v1" });

    c.TagActionsBy(api =>
        if (api.GroupName != null)
            return new[] { api.GroupName };

        var controllerActionDescriptor = api.ActionDescriptor as ControllerActionDescriptor;
        if (controllerActionDescriptor != null)
            return new[] { controllerActionDescriptor.ControllerName };

        throw new InvalidOperationException("Unable to determine tag for endpoint.");
    c.DocInclusionPredicate((name, api) => true);

Now, optionally decorate controllers like:

[ApiExplorerSettings(GroupName = "Custom Group Name")]
public class MyController : ControllerBase
    // ...

Hope that helps!

Published June 18, 2020 by

undefined avatar
Ken Dale Senior Application Developer (Former)

Suggested Reading