上一节对接RAP2
配置Swagger
的API写好后,在RAP2平台导入json
配置时发现导入失败,JAVA团队写的就OK.
在移动端同事的帮助下,发现JAVA项目写出来的接口,在根节点是有配制Tags
属性的(里面配置了控制器信息),而不管是 .NET Framework还是 .Net Core
项目 在根节点 是没有Tags
属性的,因此我就开始了百度谷歌大法。
"swagger": "2.0",
"info": {
"version": "v1",
"title": "Swagger"
},
"host": "localhost:44348",
"tags":[{"name":"order-controller","description":"Order Controller"},{"name":"test-controller","description":"Test Controller"}],
"schemes": [
"https"
],
.......
.NETCORE
经过搜索发现.Netcore实现比较简单,就是对每个控制器加上Swagger
注解
首先引用 Swashbuckle.AspNetCore.Annotations;
注解包 在控制器上加上 SwaggerTag
属性
然后运行就ok了
访问 https://localhost:44356/swagger/v1/swagger.json
能够看到在根节点出现了Tags
属性,在RAP2平台上导入也ok
.NET Framework
关于 Framework
版的搜索了很久,也没有找到相关介绍,又认认真真看了一下Swagger
官方文档,确实是可以添加的。
最终还得感谢 freecodecamp 的 camperbot 给出了我想要的答案
可访问 https://www.freecodecamp.org/forum/t/arranging-operations-alphabetically-in-swashbuckle-swagger/19350
查看原文解决方案
这里我先新建一个扩展类(主要功能)
namespace TemperatureRecord.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 TemperatureRecord.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()
{
var sr = string.Format(@"{0}\bin\TemperatureRecord.xml",//这里写之前设置输出的XML
System.AppDomain.CurrentDomain.BaseDirectory);
return sr;
}
}
}
然后在 SwaggerConfig
中引用
public class SwaggerConfig
{
public static void Register()
{
var thisAssembly = typeof(SwaggerConfig).Assembly;
GlobalConfiguration.Configuration
.EnableSwagger(c =>
{
c.Schemes(new[] { "http", "https" });
//引用写好的类 c.DocumentFilter<TemperatureRecord.Swagger.Extensions.CustomDocumentFilter>();
c.SingleApiVersion("v1", "TemperatureRecord");
c.IncludeXmlComments(string.Format(@"{0}\bin\TemperatureRecord.xml", System.AppDomain.CurrentDomain.BaseDirectory));
c.DescribeAllEnumsAsStrings();
})
.EnableSwaggerUi(c =>
{
});
}
}
然后运行项目 访问 http://localhost:44346/swagger/docs/v1
在json 的末尾就有根节点中的Tags
了, 在RAP2
平台上导入ok