引用作者原話:Asp.Net的WebApi中使用Swagger作為說明和測試的頁面是非常不錯的,比起WebApiTestClient來至少在界面上的很大的提升。但是使用Swagger時如果只是一般的控制器直接放到Controller下就可以了,而如果因不同的業務需求而需要分類或者有同名的類名時時則沒辦法很好的處理。
因為業務需求需要創建域,但是Swagger并未將域添加到接口。所以需要加上以下操作才行。
安裝Swagger方法:
為了大家多看微軟官方文檔、就直接引用Swagger安裝及使用方法。以下是微軟官方文檔。
增加域接口顯示方法:
using Microsoft.AspNetCore.Mvc.ApiExplorer; using System.Collections.Generic; using System.Linq; using System.Text.RegularExpressions; namespace System.Web.Http.Description { /// <summary> /// API描述器擴展 /// </summary> public static class ApiDescriptionExtension { /// <summary> /// 獲取區域名稱 /// </summary> /// <param name="description"></param> /// <returns></returns> public static List<string> GetAreaName(this ApiDescription description) { string areaName = description.ActionDescriptor.RouteValues["area"]; string controlName = description.ActionDescriptor.RouteValues["controller"]; List<string> areaList = new List<string>(); areaList.Add(controlName); if (!string.IsNullOrEmpty(areaName)) { description.RelativePath = $"{areaName}/{controlName}/{description.RelativePath}"; } return areaList; } } }
通過接口描述擴展獲取區域及相關信息進行改寫擴展。
使用說明:
services.AddSwaggerGen(c => { c.SwaggerDoc("v1", new Swashbuckle.AspNetCore.Swagger.Info { Version = "v1.0.0", Description = description, TermsOfService = "你的公司", Contact = new Swashbuckle.AspNetCore.Swagger.Contact { Name = "Blog.Core", Email = "Blog.Core@xxx.com", Url = "https://www.jianshu.com/u/94102b59cc2a" } }); //使用域描述 c.TagActionsBy(apiDesc => apiDesc.GetAreaName()); var basePath = PlatformServices.Default.Application.ApplicationBasePath; var xmlPath = Path.Combine(basePath, xmlName);//這個就是剛剛配置的xml文件名 c.IncludeXmlComments(xmlPath, true);//默認的第二個參數是false,這個是controller的注釋,記得修改 });
紅色部分加入代碼即可。
結果展示:
以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持服務器之家。