csharp 在Swashbuckle Swagger中,此片段允许按字母顺序显示操作。

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了csharp 在Swashbuckle Swagger中,此片段允许按字母顺序显示操作。相关的知识,希望对你有一定的参考价值。

c.DocumentFilter<YourNamespace.Swagger.Extensions.CustomDocumentFilter>();
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");
        }
    }
}

以上是关于csharp 在Swashbuckle Swagger中,此片段允许按字母顺序显示操作。的主要内容,如果未能解决你的问题,请参考以下文章

csharp Swashbuckle operationsfilter用于标题版本控制

csharp SwashBuckle配置

csharp Swashbuckle(Swagger)中的默认模型示例

ABP/Swashbuckle - 使用 Swashbuckle CLI 生成 swagger 文档

Swashbuckle 承载授权

ASP.NET 核心:NSwag 与 Swashbuckle