Swagger生成webapi文档
作者:互联网
WebApi接口开发完毕后,交付给前端人员或手机端开发者时接口说明文档是必不可少的配套设备,如果公司流程不规范大家使用口口相传的交接方式,而且没有改进的欲望,那你可以到此为止了。Swagger是方便测试接口,快速展示注释内容,生成Restful风格接口文档的框架。
Swagger能成为最受欢迎的REST APIs文档生成工具之一,有以下几个原因:
Swagger 可以生成一个具有互动性的API控制台,开发者可以用来快速学习和尝试API。
Swagger 可以生成客户端SDK代码用于各种不同的平台上的实现。
Swagger 文件可以在许多不同的平台上从代码注释中自动生成。
Swagger 有一个强大的社区,里面有许多强悍的贡献者。
1、安装Swashbuckle
2、初次运行 输入 自己网站地址/swagger 我这里是http://www.permissionapi.com/swagger
3、添加自定义ApiController
- public class AdminController : ApiController
- {
- /// <summary>
- /// 获取管理员信息
- /// </summary>
- /// <param name="username">管理员姓名</param>
- /// <param name="pwd">管理员密码</param>
- /// <returns></returns>
- public string Get(string username,string pwd)
- {
- return $"username:{username},pwd:{pwd}";
- }
- }
4、添加实现了ISwaggerProvider接口的类
在App_Start文件夹中添加SwaggerControllerDescProvider.cs,相关代码如下:
- namespace WebApiSwagger.Main.App_Start
- {
- /// <summary>
- /// 显示swagger控制器的描述
- /// </summary>
- public class SwaggerControllerDescProvider : ISwaggerProvider
- {
- private readonly ISwaggerProvider _swaggerProvider;
- private static ConcurrentDictionary<string, SwaggerDocument> _cache = new ConcurrentDictionary<string, SwaggerDocument>();
- private readonly string _xml;
- /// <summary>
- ///
- /// </summary>
- /// <param name="swaggerProvider"></param>
- /// <param name="xml">xml文档路径</param>
- public SwaggerControllerDescProvider(ISwaggerProvider swaggerProvider, string xml)
- {
- _swaggerProvider = swaggerProvider;
- _xml = xml;
- }
- public SwaggerDocument GetSwagger(string rootUrl, string apiVersion)
- {
- var cacheKey = string.Format("{0}_{1}", rootUrl, apiVersion);
- SwaggerDocument srcDoc = null;
- //只读取一次
- if (!_cache.TryGetValue(cacheKey, out srcDoc))
- {
- srcDoc = _swaggerProvider.GetSwagger(rootUrl, apiVersion);
- srcDoc.vendorExtensions = new Dictionary<string, object> { { "ControllerDesc", GetControllerDesc() } };
- _cache.TryAdd(cacheKey, srcDoc);
- }
- return srcDoc;
- }
- /// <summary>
- /// 从API文档中读取控制器描述
- /// </summary>
- /// <returns>所有控制器描述</returns>
- public ConcurrentDictionary<string, string> GetControllerDesc()
- {
- string xmlpath = _xml;
- ConcurrentDictionary<string, string> controllerDescDict = new ConcurrentDictionary<string, string>();
- if (File.Exists(xmlpath))
- {
- XmlDocument xmldoc = new XmlDocument();
- xmldoc.Load(xmlpath);
- string type = string.Empty, path = string.Empty, controllerName = string.Empty;
- string[] arrPath;
- int length = -1, cCount = "Controller".Length;
- XmlNode summaryNode = null;
- foreach (XmlNode node in xmldoc.SelectNodes("//member"))
- {
- type = node.Attributes["name"].Value;
- if (type.StartsWith("T:"))
- {
- //控制器
- arrPath = type.Split('.');
- length = arrPath.Length;
- controllerName = arrPath[length - 1];
- if (controllerName.EndsWith("Controller"))
- {
- //获取控制器注释
- summaryNode = node.SelectSingleNode("summary");
- string key = controllerName.Remove(controllerName.Length - cCount, cCount);
- if (summaryNode != null && !string.IsNullOrEmpty(summaryNode.InnerText) && !controllerDescDict.ContainsKey(key))
- {
- controllerDescDict.TryAdd(key, summaryNode.InnerText.Trim());
- }
- }
- }
- }
- }
- return controllerDescDict;
- }
- }
- }
5、添加功能性js文件
在Scripts文件夹中添加SwaggerConfig.js脚本文件,将其设置为“嵌入的资源”。这个js文件的功能主要有两个:一个是汉化,另一个是在界面上显示控制器的描述文字。
代码如下:
- 'use strict';
- window.SwaggerTranslator = {
- _words: [],
- translate: function () {
- var $this = this;
- $('[data-sw-translate]').each(function () {
- $(this).html($this._tryTranslate($(this).html()));
- $(this).val($this._tryTranslate($(this).val()));
- $(this).attr('title', $this._tryTranslate($(this).attr('title')));
- });
- },
- setControllerSummary: function () {
- $.ajax({
- type: "get",
- async: true,
- url: $("#input_baseUrl").val(),
- dataType: "json",
- success: function (data) {
- var summaryDict = data.ControllerDesc;
- var id, controllerName, strSummary;
- $("#resources_container .resource").each(function (i, item) {
- id = $(item).attr("id");
- if (id) {
- controllerName = id.substring(9);
- strSummary = summaryDict[controllerName];
- if (strSummary) {
- $(item).children(".heading").children(".options").first().prepend('<li class="controller-summary" title="' + strSummary + '">' + strSummary + '</li>');
- }
- }
- });
- }
- });
- },
- _tryTranslate: function (word) {
- return this._words[$.trim(word)] !== undefined ? this._words[$.trim(word)] : word;
- },
- learn: function (wordsMap) {
- this._words = wordsMap;
- }
- };
- /* jshint quotmark: double */
- window.SwaggerTranslator.learn({
- "Warning: Deprecated": "警告:已过时",
- "Implementation Notes": "实现备注",
- "Response Class": "响应类",
- "Status": "状态",
- "Parameters": "参数",
- "Parameter": "参数",
- "Value": "值",
- "Description": "描述",
- "Parameter Type": "参数类型",
- "Data Type": "数据类型",
- "Response Messages": "响应消息",
- "HTTP Status Code": "HTTP状态码",
- "Reason": "原因",
- "Response Model": "响应模型",
- "Request URL": "请求URL",
- "Response Body": "响应体",
- "Response Code": "响应码",
- "Response Headers": "响应头",
- "Hide Response": "隐藏响应",
- "Headers": "头",
- "Try it out!": "试一下!",
- "Show/Hide": "显示/隐藏",
- "List Operations": "显示操作",
- "Expand Operations": "展开操作",
- "Raw": "原始",
- "can't parse JSON. Raw result": "无法解析JSON. 原始结果",
- "Model Schema": "模型架构",
- "Model": "模型",
- "apply": "应用",
- "Username": "用户名",
- "Password": "密码",
- "Terms of service": "服务条款",
- "Created by": "创建者",
- "See more at": "查看更多:",
- "Contact the developer": "联系开发者",
- "api version": "api版本",
- "Response Content Type": "响应Content Type",
- "fetching resource": "正在获取资源",
- "fetching resource list": "正在获取资源列表",
- "Explore": "浏览",
- "Show Swagger Petstore Example Apis": "显示 Swagger Petstore 示例 Apis",
- "Can't read from server. It may not have the appropriate access-control-origin settings.": "无法从服务器读取。可能没有正确设置access-control-origin。",
- "Please specify the protocol for": "请指定协议:",
- "Can't read swagger JSON from": "无法读取swagger JSON于",
- "Finished Loading Resource Information. Rendering Swagger UI": "已加载资源信息。正在渲染Swagger UI",
- "Unable to read api": "无法读取api",
- "from path": "从路径",
- "server returned": "服务器返回"
- });
- $(function () {
- window.SwaggerTranslator.translate();
- window.SwaggerTranslator.setControllerSummary();
- });
6、修改SwaggerConfig.cs
Swagger安装完毕后App_Start文件夹下才会有SwaggerConfig.cs文件,修改后的SwaggerConfig.cs的代码如下:
注意代码中 JiaHua.Permission.Api是项目名称,请改成自己项目对应的名称!
- public class SwaggerConfig
- {
- public static void Register()
- {
- var thisAssembly = typeof(SwaggerConfig).Assembly;
- GlobalConfiguration.Configuration
- .EnableSwagger(c =>
- {
- c.SingleApiVersion("v1", "JiaHua.Permission.Api");
- //添加下述代码
- var xmlFile = string.Format("{0}/bin/JiaHua.Permission.Api.XML", System.AppDomain.CurrentDomain.BaseDirectory);
- if (System.IO.File.Exists(xmlFile))
- {
- c.IncludeXmlComments(xmlFile);
- }
- c.ResolveConflictingActions(apiDescriptions => apiDescriptions.First());
- c.CustomProvider((defaultProvider) => new SwaggerControllerDescProvider(defaultProvider, xmlFile));
- })
- .EnableSwaggerUi(b =>
- {
- b.InjectJavaScript(Assembly.GetExecutingAssembly(), "JiaHua.Permission.Api.Scripts.SwaggerConfig.js");
- });
- }
- }
7、修改项目的“XML文档文件”属性
右键项目--》属性--》生成
8、注释显示成功
9、小瑕疵及解决方法
<li class="tool-item tool-active is-like "><a href="javascript:;"><svg class="icon" aria-hidden="true">
<use xlink:href="#csdnc-thumbsup"></use>
</svg><span class="name">点赞</span>
<span class="count"></span>
</a></li>
<li class="tool-item tool-active is-collection "><a href="javascript:;" data-report-click="{"mod":"popu_824"}"><svg class="icon" aria-hidden="true">
<use xlink:href="#icon-csdnc-Collection-G"></use>
</svg><span class="name">收藏</span></a></li>
<li class="tool-item tool-active is-share"><a href="javascript:;"><svg class="icon" aria-hidden="true">
<use xlink:href="#icon-csdnc-fenxiang"></use>
</svg>分享</a></li>
<!--打赏开始-->
<!--打赏结束-->
<li class="tool-item tool-more">
<a>
<svg t="1575545411852" class="icon" viewBox="0 0 1024 1024" version="1.1" xmlns="http://www.w3.org/2000/svg" p-id="5717" xmlns:xlink="http://www.w3.org/1999/xlink" width="200" height="200"><defs><style type="text/css"></style></defs><path d="M179.176 499.222m-113.245 0a113.245 113.245 0 1 0 226.49 0 113.245 113.245 0 1 0-226.49 0Z" p-id="5718"></path><path d="M509.684 499.222m-113.245 0a113.245 113.245 0 1 0 226.49 0 113.245 113.245 0 1 0-226.49 0Z" p-id="5719"></path><path d="M846.175 499.222m-113.245 0a113.245 113.245 0 1 0 226.49 0 113.245 113.245 0 1 0-226.49 0Z" p-id="5720"></path></svg>
</a>
<ul class="more-box">
<li class="item"><a class="article-report">文章举报</a></li>
</ul>
</li>
</ul>
</div>
<div class="right-toolbox"><a href="https://blog.csdn.net/xiaouncle/article/details/83995809" target="_blank" class="jump-net-article">
<svg t="1575545252354" class="icon" viewBox="0 0 1024 1024" version="1.1" xmlns="http://www.w3.org/2000/svg" p-id="5597" xmlns:xlink="http://www.w3.org/1999/xlink" width="200" height="200"><defs><style type="text/css"></style></defs><path d="M243.9 1022.2c-62.3 0-124-23.8-171.5-70.8C26.4 905.5 1.5 845 1.5 779.9s24.9-125.6 70.8-171.5l184-184.1c45.9-45.9 106.4-70.8 171.5-70.8s125.6 24.9 171.5 70.8c18.1 18.1 18.1 47 0 65.1s-47 18.1-65.1 0c-28.3-28.3-65.7-43.5-105.9-43.5s-78.1 15.3-105.9 43.7l-184 184c-58.3 58.3-58.3 153.4 0 212.3 28.3 28.3 65.7 43.5 105.9 43.5s78.1-15.3 105.9-43.5l184-184c18.1-18.1 47-18.1 65.1 0 18.1 18.1 18.1 47 0 65.1l-184 184c-46.9 48-109.1 71.2-171.4 71.2z m523.7-423l184-184c94.5-94.5 94.5-248 0-342.5s-248-94.5-342.5 0l-184 184c-18.1 18.1-18.1 47 0 65.1s47 18.1 65.1 0l184-184c28.3-28.3 65.7-43.5 105.9-43.5s78.1 15.3 105.9 43.5c58.3 58.3 58.3 153.4 0 212.3l-184 184c-58.3 58.3-153.4 58.3-212.3 0-18.1-18.1-47-18.1-65.1 0-18.1 18.1-18.1 47 0 65.1 47 47 109.3 70.8 171.5 70.8s123.9-23.2 171.5-70.8z" p-id="5598"></path></svg>
站内首发文章</a></div>
</div>
<div class="person-messagebox">
<div class="left-message"><a href="https://blog.csdn.net/huan13479195089">
<img src="https://profile.csdnimg.cn/B/B/D/3_huan13479195089" class="avatar_pic" username="huan13479195089">
<img src="https://g.csdnimg.cn/static/user-reg-year/2x/10.png" class="user-years">
</a></div>
<div class="middle-message">
<div class="title"><span class="tit"><a href="https://blog.csdn.net/huan13479195089" data-report-click="{"mod":"popu_379"}" target="_blank">sufengmarket</a></span>
</div>
<div class="text"><span>发布了13 篇原创文章</span> · <span>获赞 1</span> · <span>访问量 4350</span></div>
</div>
<div class="right-message">
<a href="https://im.csdn.net/im/main.html?userName=huan13479195089" target="_blank" class="btn btn-sm btn-red-hollow bt-button personal-letter">私信
</a>
<a class="btn btn-sm attented bt-button personal-watch" data-report-click="{"mod":"popu_379"}">已关注</a>
</div>
</div>
</div>
み旋律
发布了20 篇原创文章 · 获赞 0 · 访问量 777
私信
关注
标签:webapi,function,string,public,文档,controllerName,Swagger,Response 来源: https://blog.csdn.net/weixin_44481764/article/details/104503075