欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

Swagger实例分享(VS+WebApi+Swashbuckle)

程序员文章站 2022-04-28 20:30:45
Swagger实例分享(VS+WebApi+Swashbuckle) Swagger可以很方便的为发布的WebApi自动生成优雅的文档,不需额外自己编写,只需为项目配置好,是一个很好用的工具,做一个简单的Demo和大家分享一下~ 1、使用HuGet导入Swashbuckle包 2、修改Swagger ......

swagger实例分享(vs+webapi+swashbuckle)

  swagger可以很方便的为发布的webapi自动生成优雅的文档,不需额外自己编写,只需为项目配置好,是一个很好用的工具,做一个简单的demo和大家分享一下~

 

1、使用huget导入swashbuckle包

Swagger实例分享(VS+WebApi+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、配置项目属性

Swagger实例分享(VS+WebApi+Swashbuckle)

主要是设置“生成”下的几个配置,就是我画红框框的,下面解释一下几个配置的作用:

(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(网址端口看自己的项目),可以看到如下界面就是成功了:

Swagger实例分享(VS+WebApi+Swashbuckle)

  页面会将接口路径、接口函数、注释、参数等基本信息都自动生成,还提供接口测试功能(单击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设置为“嵌入的资源”

属性->生成操作->设置为“嵌入的资源”

Swagger实例分享(VS+WebApi+Swashbuckle)

 

(3)配置swaggerconfig.cs

在enableswaggerui下添加:
c.injectjavascript(assembly.getexecutingassembly(), "mywebapi.scripts.swagger_cn.js");  
注:mywebapi.scripts.swagger_cn.js格式为:项目名.文件夹名.js文件名


这个可以看上面的swaggerconfig.cs文件配置。然后再次运行:

Swagger实例分享(VS+WebApi+Swashbuckle)

  现在就可以看到你日思夜想的中文了~