Search code examples
c#asp.netasp.net-coreswaggeropenapi

Change Order of Tags using Swagger in C#


I´m currently changing our ASP.NET API to the OpenAPI format and thus I use Swagger to generate the API File automatically.

There seems to be no way of defining the Order of these Tags globally. Additionally I would like to add descriptions to each tag.

Any Ideas?

I´ve already found out that I can add Tags to Controllers and Methods using the [Tags] Attribute, and I know, that I can add tag descriptions and stuff directly in the generated yaml, but I would like completely create the yaml using swagger in ASP.NET.

My code looks like this: Program.cs

services.AddEndpointsApiExplorer();
services.AddSwaggerGen(c =>
{
    c.EnableAnnotations();
    c.OperationFilter<TagOrderFilter>();
    c.SwaggerDoc("v1", new OpenApiInfo
    {
        Title = "InboundApp",
        Version = "v1",
        Description = "bla",
    });
    
});

Controller:

[ApiExplorerSettings(IgnoreApi = false)]
[Tags("Finishing the import")]
[HttpPatch("{id}", Name = nameof(ImportProcessController) +`"." + nameof(PatchImportProcess))]
public async Task<IActionResult> PatchImportProcess(string id, [FromBody] PatchDto patchDto)
{ ...

I do have about 6-7 Tags and multiple Tags at some controllers


Solution

  • You could try create Empty Tags with your order before endpoints use them.

        public class EmptyTagsDocumentFilter : IDocumentFilter
        {
            public void Apply(OpenApiDocument swaggerDoc, DocumentFilterContext context)
            {
                // Add empty tags to the Swagger document
                swaggerDoc.Tags.Add(new OpenApiTag { Name = "Tag3" });
                swaggerDoc.Tags.Add(new OpenApiTag { Name = "Tag2" });
                swaggerDoc.Tags.Add(new OpenApiTag { Name = "Tag1" });
            }
        }
    

    Then in program.cs

    builder.Services.AddSwaggerGen(c =>
    {
        c.EnableAnnotations();
        c.DocumentFilter<EmptyTagsDocumentFilter>();
    };
    

    Test result
    enter image description here