Explorar o código

Swagger修改

zoulei hai 1 ano
pai
achega
f0d90cb0d9
Modificáronse 3 ficheiros con 121 adicións e 12 borrados
  1. 112 6
      XdCxRhDW.App/WebAPI/Startup.cs
  2. 1 0
      XdCxRhDW.App/WebAPI/Swagger.js
  3. 8 6
      XdCxRhDw.Dto/DetectDto.cs

+ 112 - 6
XdCxRhDW.App/WebAPI/Startup.cs

@@ -1,13 +1,16 @@
 using System;
 using System.Collections.Concurrent;
 using System.Collections.Generic;
+using System.ComponentModel;
 using System.ComponentModel.DataAnnotations;
 using System.IO;
 using System.Linq;
 using System.Net;
 using System.Net.Http;
+using System.Reflection;
 using System.Runtime.Remoting.Contexts;
 using System.Text;
+using System.Threading;
 using System.Web.Http;
 using System.Web.Http.Description;
 using System.Web.Http.Filters;
@@ -16,6 +19,7 @@ using System.Web.Http.Routing;
 using System.Web.Http.Validation;
 using System.Web.Http.Validation.Providers;
 using System.Xml;
+using System.Xml.Linq;
 using Microsoft.Owin;
 using Microsoft.Owin.Cors;
 using Newtonsoft.Json;
@@ -47,12 +51,16 @@ namespace XdCxRhDW.App.WebAPI
                 //日期类型默认格式化处理
                 DateFormatHandling = DateFormatHandling.MicrosoftDateFormat,
                 DateFormatString = "yyyy-MM-dd HH:mm:ss",
+
                 //驼峰样式
-                ContractResolver = new CamelCasePropertyNamesContractResolver(),
+                //ContractResolver = new CamelCasePropertyNamesContractResolver(),
+
                 //空值处理
                 //NullValueHandling = NullValueHandling.Ignore,
+
                 //设置序列化的最大层数
                 MaxDepth = 10,
+
                 //解决json序列化时的循环引用问题
                 ReferenceLoopHandling = ReferenceLoopHandling.Ignore
             };
@@ -69,8 +77,6 @@ namespace XdCxRhDW.App.WebAPI
             //添加路由路径
             config.MapHttpAttributeRoutes();
             app.UseCors(CorsOptions.AllowAll);
-
-            //app.Use<LoggingMiddleware>();
             app.UseWebApi(config);
         }
         private static void ConfigureSwagger(HttpConfiguration config)
@@ -78,22 +84,27 @@ namespace XdCxRhDW.App.WebAPI
             var thisAssembly = typeof(Startup).Assembly;
             config.EnableSwagger(c =>
              {
+                 c.IgnoreObsoleteActions();//忽略过时的方法
+                 c.IgnoreObsoleteProperties();//忽略过时的属性
+                 c.PrettyPrint();//漂亮缩进
                  c.SingleApiVersion("v1", "多模式融合定位平台Http接口");
+                 c.ApiKey("123456");
 
                  //设置接口描述xml路径地址
                  var webApiXmlPath1 = $"{AppDomain.CurrentDomain.BaseDirectory}{Path.GetFileNameWithoutExtension(System.AppDomain.CurrentDomain.FriendlyName)}.xml";
                  c.IncludeXmlComments(webApiXmlPath1);
                  var webApiXmlPath2 = $"{AppDomain.CurrentDomain.BaseDirectory}XdCxRhDw.Dto.xml";
                  c.IncludeXmlComments(webApiXmlPath2);
-                 c.UseFullTypeNameInSchemaIds();
+                 //c.UseFullTypeNameInSchemaIds();//使用完整类型名称
                  //加入控制器描述
                  c.CustomProvider((defaultProvider) => new SwaggerControllerDescProvider(defaultProvider, webApiXmlPath1));
                  c.OperationFilter<FileUploadOperation>();
+                 c.SchemaFilter<SwaggerEnumFilter>();
              })
              .EnableSwaggerUi(c =>
              {
                  c.InjectJavaScript(thisAssembly, "XdCxRhDW.App.WebAPI.Swagger.js");
-                 c.DocumentTitle("");
+                 c.DocumentTitle("多模式融合定位平台Http接口");
              });
         }
         /// <summary>
@@ -126,7 +137,7 @@ namespace XdCxRhDW.App.WebAPI
             /// </summary>
             public string Description { get; private set; }
         }
-       
+
         public class FileUploadOperation : IOperationFilter
         {
             public void Apply(Operation operation, SchemaRegistry schemaRegistry, ApiDescription apiDescription)
@@ -273,8 +284,103 @@ namespace XdCxRhDW.App.WebAPI
                 return controllerDescDict;
             }
         }
+
+        private sealed class ApiComparer : IComparer<string>
+        {
+            public int Compare(string x, string y)
+            {
+                return x.CompareTo(y);
+            }
+        }
     }
 
+    public class SwaggerEnumFilter : ISchemaFilter
+    {
+        public void Apply(Schema schema, SchemaRegistry schemaRegistry, Type type)
+        {
+            UpdateSchemaDescription(schema, type);
+        }
+        private void UpdateSchemaDescription(Schema schema, Type type)
+        {
+            if (type.IsEnum)//枚举直接应用在controller接口中
+            {
+                var items = GetEnumInfo(type);
+                if (items.Length > 0)
+                {
+                    var description = GetEnumInfo(type);
+                    schema.description = string.IsNullOrEmpty(schema.description) ? description : $"{schema.description}:{description}";
+                }
+            }
+            else if (type.IsClass && type != typeof(string))//枚举在类的属性中
+            {
+                if (schema.properties == null) return;
+                var props = type.GetProperties();
+                foreach (var prop in props)
+                {
+                    var propScheama = schema.properties[prop.Name];
+                    if (prop.PropertyType.IsClass && prop.PropertyType != typeof(string))
+                    {
+                        UpdateSchemaDescription(propScheama, prop.PropertyType);
+                    }
+                    else
+                    {
+                        if (prop.PropertyType.IsEnum)
+                        {
+                            var description = GetEnumInfo(prop.PropertyType);
+                            propScheama.description = string.IsNullOrWhiteSpace(propScheama.description) ? description : $"{propScheama.description}:{description}";
+                            propScheama.@enum = null;
+                        }
+                    }
+                }
+            }
+        }
+        /// <summary>
+        /// 获取枚举值+描述  
+        /// </summary>
+        /// <param name="enumType"></param>
+        /// <returns></returns>
+        private string GetEnumInfo(Type enumType)
+        {
+            var fields = enumType.GetFields();
+            List<string> list = new List<string>();
+            foreach (var field in fields)
+            {
+                if (!field.FieldType.IsEnum) continue;
+                string description = null;
+                if (description == null)//取DescriptionAttribute的值
+                {
+                    var descriptionAttr = field.GetCustomAttribute<DescriptionAttribute>();
+                    if (descriptionAttr != null && !string.IsNullOrWhiteSpace(descriptionAttr.Description))
+                    {
+                        description = descriptionAttr.Description;
+                    }
+                }
+                if (description == null)//取DisplayAttribute的值
+                {
+                    var dispalyAttr = field.GetCustomAttribute<DisplayAttribute>();
+                    if (dispalyAttr != null && !string.IsNullOrWhiteSpace(dispalyAttr.Name))
+                    {
+                        description = dispalyAttr.Name;
+                    }
+                }
+                if (description == null)//取DisplayNameAttribute的值
+                {
+                    var dispalyNameAttr = field.GetCustomAttribute<DisplayNameAttribute>();
+                    if (dispalyNameAttr != null && !string.IsNullOrWhiteSpace(dispalyNameAttr.DisplayName))
+                    {
+                        description = dispalyNameAttr.DisplayName;
+                    }
+                }
+                if (description == null)//取字段名
+                {
+                    description = field.Name;
+                }
+                var value = field.GetValue(null);
+                list.Add($"{description}={(int)value}");
+            }
+            return string.Join(",", list);
+        }
+    }
     public class CustomModelValidator : ModelValidator
     {
         public CustomModelValidator(IEnumerable<ModelValidatorProvider> modelValidatorProviders) : base(modelValidatorProviders)

+ 1 - 0
XdCxRhDW.App/WebAPI/Swagger.js

@@ -100,6 +100,7 @@ window.SwaggerTranslator.learn({
 
 
 $(function () {
+    $(".swagger-ui-wrap").css("max-width", "80%");
     window.SwaggerTranslator.translate();
     window.SwaggerTranslator.setControllerSummary();
     // document.title = "API描述文档";

+ 8 - 6
XdCxRhDw.Dto/DetectDto.cs

@@ -1,5 +1,6 @@
 using System;
 using System.Collections.Generic;
+using System.ComponentModel;
 using System.ComponentModel.DataAnnotations;
 using System.Linq;
 using System.Text;
@@ -15,9 +16,10 @@ namespace XdCxRhDw.Dto
         /// <summary>
         /// 调用Upload接口上传文件后返回的文件名
         /// </summary>
+        [DefaultValue("hello word!")]
         public string file1 { get; set; }
         /// <summary>
-        /// 检测类型(DAMA=1,IBS=2,能量检测=3) 
+        /// 检测类型
         /// </summary>
         public DmcType dmcType { get; set; }
 
@@ -34,19 +36,19 @@ namespace XdCxRhDw.Dto
         /// <summary>
         /// DAMA检测
         /// </summary>
-        [Display(Name ="DAMA")]
-        DAMA=1,
+        [Display(Name = "DAMA检测")]
+        DAMA = 1,
 
         /// <summary>
         /// IBS检测
         /// </summary>
-        [Display(Name = "IBS")]
-        IBS =2,
+        [Display(Name = "IBS检测")]
+        IBS = 2,
 
         /// <summary>
         /// 能量检测
         /// </summary>
         [Display(Name = "能量检测")]
-        Ky5758 =3
+        Ky5758 = 3
     }
 }