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文件配置。然后再次运行:
现在就可以看到你日思夜想的中文了~