Search code examples
c#.netasp.net-coreswaggerswagger-ui

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");
});


Solution

  • 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>();
    });