十年河東,十年河西,莫欺少年窮
學無止境,精益求精
net6集成了swagger的基礎功能,但功能不夠用
因此只能自定義擴展方法了,如下
1、集成Jwt授權
將
builder.Services.AddSwaggerGen();
改成
builder.Services.AddSwaggerGen(c => { var scheme = new OpenApiSecurityScheme() { Description = "Authorization header. \r\nExample: 'Bearer abcdefxxx'", Reference = new OpenApiReference { Type = ReferenceType.SecurityScheme, Id = "Authorization" }, Scheme = "oauth2", Name = "Authorization", In = ParameterLocation.Header, Type = SecuritySchemeType.ApiKey, }; c.AddSecurityDefinition("Authorization", scheme); var requirement = new OpenApiSecurityRequirement(); requirement[scheme] = new List<string>(); c.AddSecurityRequirement(requirement); });
2、增加Swagger註釋
增加swagger註釋後,測試人員/前段開發人員就可以自己看文檔了,省的在開發人員面前嘰嘰歪歪
2.1、設置Model層和Api層項目XML輸出
代碼如下:
builder.Services.AddSwaggerGen(c => { var basePath = Path.GetDirectoryName(AppContext.BaseDirectory); //c.IncludeXmlComments(Path.Combine(basePath, Assembly.GetExecutingAssembly().GetName().Name+".xml"), true); c.IncludeXmlComments(Path.Combine(basePath, "swap.xml"), true); c.IncludeXmlComments(Path.Combine(basePath, "swapModels.xml"), true); // var scheme = new OpenApiSecurityScheme() { Description = "Authorization header. \r\nExample: 'Bearer 12345abcdef'", Reference = new OpenApiReference { Type = ReferenceType.SecurityScheme, Id = "Authorization" }, Scheme = "oauth2", Name = "Authorization", In = ParameterLocation.Header, Type = SecuritySchemeType.ApiKey, }; c.AddSecurityDefinition("Authorization", scheme); var requirement = new OpenApiSecurityRequirement(); requirement[scheme] = new List<string>(); c.AddSecurityRequirement(requirement); });
3、自定義屬性隱藏及Api方法隱藏
3.1、Api層新建swagger過濾器
using Microsoft.OpenApi.Models; using swapCommon;//HiddenFieldAttribute 和 HiddenAttribute 在公共類庫存 using Swashbuckle.AspNetCore.SwaggerGen; using System; using System.Collections.Generic; using System.Linq; using System.Net.Http; using System.Reflection; using System.Text; namespace swapInit { public class HiddenApiFilter : IDocumentFilter { public void Apply(OpenApiDocument swaggerDoc, DocumentFilterContext context) { foreach (var item in context.ApiDescriptions) { if (item.TryGetMethodInfo(out MethodInfo methodInfo)) { if (methodInfo.ReflectedType.CustomAttributes.Any(t => t.AttributeType == typeof(HiddenAttribute)) || methodInfo.CustomAttributes.Any(t => t.AttributeType == typeof(HiddenAttribute))) { var key = "/" + item.RelativePath.TrimEnd('/'); if (key.Contains("?")) { int idx = key.IndexOf("?", StringComparison.Ordinal); key = key.Substring(0, idx); } if (swaggerDoc.Paths.ContainsKey(key)) { swaggerDoc.Paths.Remove(key); } } } } } } public class HiddenFieldFilter : ISchemaFilter { public void Apply(OpenApiSchema schema, SchemaFilterContext context) { if (schema?.Properties == null) { return; } var name = context.Type.FullName; var excludedProperties = context.Type.GetProperties(); foreach (var property in excludedProperties) { var attribute = property.GetCustomAttribute<HiddenFieldAttribute>(); if (attribute != null && schema.Properties.ContainsKey(ToLowerStart(property.Name))) { schema.Properties.Remove(ToLowerStart(property.Name)); } }; } public static string ToLowerStart( string source) { if (string.IsNullOrWhiteSpace(source)) { return source; } var start = source.Substring(0, 1); return $"{start.ToLower()}{source.Substring(1, source.Length - 1)}"; } } }
3.2、公共類庫層新建屬性類
using System; using System.Collections.Generic; using System.Text; namespace swapCommon { [AttributeUsage(AttributeTargets.Property)] public class HiddenFieldAttribute : Attribute { } [AttributeUsage(AttributeTargets.Method | AttributeTargets.Class)] public class HiddenAttribute : Attribute { } }
3.3、引用上述過濾器
builder.Services.AddSwaggerGen(c => { var basePath = Path.GetDirectoryName(AppContext.BaseDirectory); //c.IncludeXmlComments(Path.Combine(basePath, Assembly.GetExecutingAssembly().GetName().Name+".xml"), true); c.IncludeXmlComments(Path.Combine(basePath, "swap.xml"), true); c.IncludeXmlComments(Path.Combine(basePath, "swapModels.xml"), true); // c.DocumentFilter<HiddenApiFilter>(); c.SchemaFilter<HiddenFieldFilter>(); // var scheme = new OpenApiSecurityScheme() { Description = "Authorization header. \r\nExample: 'Bearer 12345abcdef'", Reference = new OpenApiReference { Type = ReferenceType.SecurityScheme, Id = "Authorization" }, Scheme = "oauth2", Name = "Authorization", In = ParameterLocation.Header, Type = SecuritySchemeType.ApiKey, }; c.AddSecurityDefinition("Authorization", scheme); var requirement = new OpenApiSecurityRequirement(); requirement[scheme] = new List<string>(); c.AddSecurityRequirement(requirement); });
3.4、測試Swagger過濾器
3.4.1、定義一個Post方法
/// <summary> /// 演示字段隱藏 /// </summary> /// <param name="stdto"></param> /// <returns></returns> [HttpPost] [Route("GetStdto")] public IActionResult GetStdto([FromBody]stdto stdto) { var dt = DateTime.Now; return Ok(dt ); }
3.4.2、定義參數實體
有了身份證號,可以自動計算出年齡等場景,總之不想讓測試和前端人員看到,省的他們嘰嘰歪歪
public class stdto { public string name { get; set; } public string IdCard { get; set; } /// <summary> /// 該字段會在swagger中隱藏 /// </summary> [HiddenField] public int age { get; set; } }
3.5、[Hidden]隱藏 Action 方法
不想讓測試或前端在swagger上看到某方法,那就隱藏,省的他們嘰嘰歪歪
/// <summary> /// 演示Api隱藏 ,該方法不會展示在swagger上 /// </summary> /// <param name="Hs">https://www.cnblogs.com/catcher1994/p/responsecaching.html</param> /// <returns></returns> [HttpGet] [Hidden] [Route("GetTime")] public IActionResult GetTime() { var dt = DateTime.Now; return Ok(dt); }
不作截圖演示了。
4、規定項目時間返回格式
嚴格來說這個和swagger沒關,但...分享是一種美德
4.1、公共類庫層先建JsonResult格式化類
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Text.Json; using System.Text.Json.Serialization; namespace swapCommon.Ext { public class JsonOptionsExt : JsonConverter<DateTime> { private readonly string Format; public JsonOptionsExt(string format = "yyyy-MM-dd HH:mm:ss") { Format = format; } public override void Write(Utf8JsonWriter writer, DateTime date, JsonSerializerOptions options) { writer.WriteStringValue(date.ToString(Format)); } public override DateTime Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) { // 獲取時間類型的字符串 var dt = reader.GetString(); if (!string.IsNullOrEmpty(dt)) { //將日期與時間之間的"T"替換爲一個空格,將結尾的"Z"去掉,否則會報錯 dt = dt.Replace("T", " ").Replace("Z", ""); //取到秒,毫秒內容也要去掉,經過測試,不去掉會報錯 if (dt.Length > 19) { dt = dt.Substring(0, 19); } return DateTime.ParseExact(dt, Format, null); } return DateTime.Now; } } }
4.2、添加控制器時引用
builder.Services.AddControllers()
改成
builder.Services.AddControllers().AddJsonOptions(options => { //時間格式化響應 options.JsonSerializerOptions.Converters.Add(new JsonOptionsExt()); });
改好後,時間的返回就統一了
ok,截止到這兒,就over了,希望前端和測試不要罵我。
@天才臥龍