Swagger實例分享(VS+WebApi+Swashbuckle) Swagger可以很方便的為發佈的WebApi自動生成優雅的文檔,不需額外自己編寫,只需為項目配置好,是一個很好用的工具,做一個簡單的Demo和大家分享一下~ 1、使用HuGet導入Swashbuckle包 2、修改Swagger ...
Swagger實例分享(VS+WebApi+Swashbuckle)
Swagger可以很方便的為發佈的WebApi自動生成優雅的文檔,不需額外自己編寫,只需為項目配置好,是一個很好用的工具,做一個簡單的Demo和大家分享一下~
1、使用HuGet導入Swashbuckle包
2、修改SwaggerConfig.cs
導入Swashbuckle後會自動在站點的App_Start文件夾下生成SwaggerConfig.cs,用於配置Swagger頁面。配置的東西很多,下麵只列舉我個人需要的簡單的配置(因為其他沒研究)。
1 public class SwaggerConfig 2 { 3 public static void Register() 4 { 5 var thisAssembly = typeof(SwaggerConfig).Assembly; 6 7 GlobalConfiguration.Configuration 8 .EnableSwagger(c => 9 { 10 c.SingleApiVersion("v1", "MyWebApi").Contact(x => 11 { 12 x.Name("Bobbie"); //配置界面頭部描述 13 }); 14 15 c.IncludeXmlComments(GetXmlCommentsPath("/bin/WarRoom.WebApi.XML")); //配置模板XML路徑 16 17 }) 18 .EnableSwaggerUi(c => 19 {
c.InjectJavaScript(Assembly.GetExecutingAssembly(), "MyWebApi.Scripts.Swagger_CN.js"); //配置漢化js文件 20 }); 21 } 22 23 private static string GetXmlCommentsPath(string XmlPath) 24 { 25 return $@"{System.AppDomain.CurrentDomain.BaseDirectory}" + XmlPath; 26 } 27 }
3、配置項目屬性
主要是設置“生成”下的幾個配置,就是我畫紅框框的,下麵解釋一下幾個配置的作用:
(1)禁止警告1591是屬於禁止缺少註釋的警告的,不然沒有頭部註釋的類、函數都會有警告的下劃線,看著不舒服(但該警告不影響使用)。
(2)勾選XML文檔文件,會自動生成一個路徑,這個路徑要於SwaggerConfig.cs中配置的一致:
c.IncludeXmlComments(GetXmlCommentsPath("/bin/WarRoom.WebApi.XML"));
由此其實已經配置完成,下麵進行測試:
4、測試
新建一個Controller,文件名為DemoController.cs:
1 public class DemoController : ApiController 2 { 3 /// <summary> 4 /// 我就是PostTest方法 5 /// </summary> 6 /// <param name="name">參數1</param> 7 /// <returns></returns> 8 [HttpGet] 9 public string PostTest(string name) 10 { 11 string result = "Hello " + name; 12 return result; 13 }
然後運行,訪問localhost:27827/Swagger(網址埠看自己的項目),可以看到如下界面就是成功了:
頁面會將介面路徑、介面函數、註釋、參數等基本信息都自動生成,還提供介面測試功能(單擊Try it Out),可以測試介面(可直接輸入參數)。
5、漢化
有些朋友喜歡中文,這邊也測試一下漢化的功能,主要就是添加一個漢化功能的JS文件,併在SwaggerConfig.cs配置導入即可:
(1)新建名為Swagger_CN.js的文件,放在Scripts文件夾下:
1 'use strict'; 2 /** 3 * Translator for documentation pages. 4 * 5 * To enable translation you should include one of language-files in your index.html 6 * after <script src='lang/translator.js' type='text/javascript'></script>. 7 * For example - <script src='lang/ru.js' type='text/javascript'></script> 8 * 9 * If you wish to translate some new texsts you should do two things: 10 * 1. Add a new phrase pair ("New Phrase": "New Translation") into your language file (for example lang/ru.js). It will be great if you add it in other language files too. 11 * 2. Mark that text it templates this way <anyHtmlTag data-sw-translate>New Phrase</anyHtmlTag> or <anyHtmlTag data-sw-translate value='New Phrase'/>. 12 * The main thing here is attribute data-sw-translate. Only inner html, title-attribute and value-attribute are going to translate. 13 * 14 */ 15 window.SwaggerTranslator = { 16 _words: [], 17 translate: function () { 18 var $this = this; 19 $('[data-sw-translate]').each(function () { 20 $(this).html($this._tryTranslate($(this).html())); 21 $(this).val($this._tryTranslate($(this).val())); 22 $(this).attr('title', $this._tryTranslate($(this).attr('title'))); 23 }); 24 }, 25 _tryTranslate: function (word) { 26 return this._words[$.trim(word)] !== undefined ? this._words[$.trim(word)] : word; 27 }, 28 learn: function (wordsMap) { 29 this._words = wordsMap; 30 } 31 }; 32 /* jshint quotmark: double */ 33 window.SwaggerTranslator.learn({ 34 "Warning: Deprecated": "警告:已過時", 35 "Implementation Notes": "實現備註", 36 "Response Class": "響應類", 37 "Status": "狀態", 38 "Parameters": "參數", 39 "Parameter": "參數", 40 "Value": "值", 41 "Description": "描述", 42 "Parameter Type": "參數類型", 43 "Data Type": "數據類型", 44 "Response Messages": "響應消息", 45 "HTTP Status Code": "HTTP狀態碼", 46 "Reason": "原因", 47 "Response Model": "響應模型", 48 "Request URL": "請求URL", 49 "Response Body": "響應體", 50 "Response Code": "響應碼", 51 "Response Headers": "響應頭", 52 "Hide Response": "隱藏響應", 53 "Headers": "頭", 54 "Try it out!": "試一下!", 55 "Show/Hide": "顯示/隱藏", 56 "List Operations": "顯示操作", 57 "Expand Operations": "展開操作", 58 "Raw": "原始", 59 "can't parse JSON. Raw result": "無法解析JSON. 原始結果", 60 "Model Schema": "模型架構", 61 "Model": "模型", 62 "apply": "應用", 63 "Username": "用戶名", 64 "Password": "密碼", 65 "Terms of service": "服務條款", 66 "Created by": "創建者", 67 "See more at": "查看更多:", 68 "Contact the developer": "聯繫開發者", 69 "api version": "api版本", 70 "Response Content Type": "響應內容類型", 71 "fetching resource": "正在獲取資源", 72 "fetching resource list": "正在獲取資源列表", 73 "Explore": "瀏覽", 74 "Show Swagger Petstore Example Apis": "顯示 Swagger Petstore 示例 Apis", 75 "Can't read from server. It may not have the appropriate access-control-origin settings.": "無法從伺服器讀取。可能沒有正確設置access-control-origin。", 76 "Please specify the protocol for": "請指定協議:", 77 "Can't read swagger JSON from": "無法讀取swagger JSON於", 78 "Finished Loading Resource Information. Rendering Swagger UI": "已載入資源信息。正在渲染Swagger UI", 79 "Unable to read api": "無法讀取api", 80 "from path": "從路徑", 81 "server returned": "伺服器返回" 82 }); 83 $(function () { 84 window.SwaggerTranslator.translate(); 85 });
(2)將Swagger_CN.js設置為“嵌入的資源”
屬性->生成操作->設置為“嵌入的資源”
(3)配置SwaggerConfig.cs
在EnableSwaggerUi下添加:
c.InjectJavaScript(Assembly.GetExecutingAssembly(), "MyWebApi.Scripts.Swagger_CN.js");
註:MyWebApi.Scripts.Swagger_CN.js格式為:項目名.文件夾名.JS文件名
這個可以看上面的SwaggerConfig.cs文件配置。然後再次運行:
現在就可以看到你日思夜想的中文了~