spaleet
spaleet

Reputation: 936

Asp.Net Core Swagger Sort Tags Alphabetically

I'm using asp.net core 6 & Swashbuckle.AspNetCore

and I'm using SwaggerAnnotations in my actions

But my Tags Groups are not ordered

Here's my Swagger UI page

enter image description here


My Program.cs :

builder.Services.AddSwaggerGen(c => {
  c.SwaggerDoc("v1", new OpenApiInfo {
    Title = "Api", Version = "v1"
  });
  c.EnableAnnotations();
});

 ....

var app = builder.Build();

app.UseSwagger();
app.UseSwaggerUI(c => {
  c.SwaggerEndpoint("/swagger/v1/swagger.json", "Shoppy.WebApi");
  c.InjectStylesheet("/swagger-ui/css/custom.css");
});

Upvotes: 10

Views: 4181

Answers (3)

user692942
user692942

Reputation: 16682

I tried the accepted answer but the swaggerDoc.Tags list was always empty, in the end I found this worked.

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

  c.SwaggerGeneratorOptions.TagsSelector = (apiDesc) => apiDesc.ActionDescriptor.EndpointMetadata.OfType<SwaggerOperationAttribute>().FirstOrDefault().Tags;
});

This forces the TagsSelector to use the Tags property from the SwaggerOperationAttribute on the Controller action.

[SwaggerOperation(
    Summary = "Get Product",
    Description = "Get a product from the shop",
    OperationId = "Product.Get",
    Tags = new[] { "Product" })
]

Upvotes: 0

JustDev14867359
JustDev14867359

Reputation: 71

Also you can do it using such configuration string

app.UseSwaggerUI(c =>
{
    c.ConfigObject.AdditionalItems.Add("tagsSorter", "alpha");
    ...
});

Upvotes: 7

spaleet
spaleet

Reputation: 936

I got the solution

I created this Custom DocumentFiler thats sorts the Tags

public class OrderTagsDocumentFilter: IDocumentFilter 
{
    public void Apply(OpenApiDocument swaggerDoc, DocumentFilterContext context) 
    {
        swaggerDoc.Tags = swaggerDoc.Tags
             .OrderBy(x => x.Name).ToList();
    }
}

and added it to Program.cs


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

  c.DocumentFilter<OrderTagsDocumentFilter>();
});

Upvotes: 11

Related Questions