Skip to content

Instantly share code, notes, and snippets.

@pallu
Last active March 4, 2016 21:48
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save pallu/0f28e98fa89d2855a321 to your computer and use it in GitHub Desktop.
Save pallu/0f28e98fa89d2855a321 to your computer and use it in GitHub Desktop.
In Swashbuckle Swagger, this snippet allows for operations to be displayed in alphabetical order.
using Swashbuckle.Swagger;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace YourNamespace.Swagger.Extensions
{
public class CustomDocumentFilter : IDocumentFilter
{
public void Apply(SwaggerDocument swaggerDoc, SchemaRegistry schemaRegistry, System.Web.Http.Description.IApiExplorer apiExplorer)
{
//make operations alphabetic
var paths = swaggerDoc.paths.OrderBy(e => e.Key).ToList();
swaggerDoc.paths = paths.ToDictionary(e => e.Key, e => e.Value);
//controller comments do not get added to swagger docs. This is how to add them.
AddControllerDescriptions(swaggerDoc, apiExplorer);
}
private static void AddControllerDescriptions(SwaggerDocument swaggerDoc, System.Web.Http.Description.IApiExplorer apiExplorer)
{
var doc = new YourPortal.Areas.HelpPage.XmlDocumentationProvider(GetXmlCommentsPath());
List<Tag> lst = new List<Tag>();
var desc = apiExplorer.ApiDescriptions;
ILookup<HttpControllerDescriptor, ApiDescription> apiGroups = desc.ToLookup(api => api.ActionDescriptor.ControllerDescriptor);
foreach (var apiGroup in apiGroups)
{
string tagName = apiGroup.Key.ControllerName;
var tag = new Tag { name = tagName };
var apiDoc = doc.GetDocumentation(apiGroup.Key);
if (!String.IsNullOrWhiteSpace(apiDoc))
tag.description = apiDoc;
lst.Add(tag);
}
if (lst.Count() > 0)
swaggerDoc.tags = lst.ToList();
}
private static string GetXmlCommentsPath()
{
//return System.Web.HttpContext.Current.Server.MapPath("~/App_Data/PortalWebAPI.XML");
return System.Web.Hosting.HostingEnvironment.MapPath("~/App_Data/PortalWebAPI.xml");
}
}
}
c.DocumentFilter<YourNamespace.Swagger.Extensions.CustomDocumentFilter>();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment