How to order endpoints based on actions in swagger using .Net Core?

Viewed 291

I have requirement of ordering the swagger endpoints based on http method types. But unfortunately it always groups based on paths. Need all endpoints segregated based on http method types as shown in below screen shot.

Target should be like below irrespective of paths,

Post Endpoints
Put Endpoints
Get Endpoints
Delete Endpoints

enter image description here

1 Answers

Here's how I managed to solve this: First create a new document filter class. Mine is:

using Microsoft.OpenApi.Models;
using Swashbuckle.AspNetCore.Annotations;
using Swashbuckle.AspNetCore.SwaggerGen;
namespace ActiveDirectoryAPI.Classes
{
    public class SwaggerOrderTagsDocumentFilter : IDocumentFilter
    {
        public void Apply(OpenApiDocument swaggerDoc, DocumentFilterContext context)
        {
            if (swaggerDoc.Tags == null) swaggerDoc.Tags = new List<OpenApiTag>();

            var swaggerList = context.ApiDescriptions.
                Select(x => x.ActionDescriptor.EndpointMetadata).
                Select(x => x.OfType<SwaggerOperationAttribute>()).
                SkipWhile(x => x == null).
                ToList();

            foreach (IEnumerable<SwaggerOperationAttribute>? item in swaggerList)
            {
                foreach (SwaggerOperationAttribute? item2 in item.Where(x => x.Tags.Length > 0))
                {
                    foreach (var t in item2.Tags)
                    {
                        if (!swaggerDoc.Tags.Any(x => x.Name == t))
                        {
                            swaggerDoc.Tags.Add(new OpenApiTag
                            {
                                Name = t,
                                Description = t
                            });
                        }
                    }
                }
            }

            swaggerDoc.Tags = swaggerDoc.Tags.OrderBy(x => x.Description).ToList();
        }
    }
}

This filter should be added to Program.cs. Inside builder.Services.AddSwaggerGen(options=>... add these 2 lines:

options.EnableAnnotations();
options.DocumentFilter<SwaggerOrderTagsDocumentFilter>();

Finally place this kinda attributes over your actions:

[SwaggerOperation(Summary = "some description here", Tags = new[] { "same tags within the same controller for each action"})]

Hope this helps.

Related