上一篇,咱们是正式将ABP生成的代码项目,跑起来了,而后演示了下多租户的不一样。那么这篇咱们就来实现下SwaggerUI。javascript
Q:SwaggerUI是干什么的呢?css
A:他是一个能将咱们的webapi,经过Swagger Api来生成一个交互式的文档。经过他能够对你的接口进行调式。html
选择PhoneBook.WebApi,而后添加nuget包(固然你也能够经过命令行添加)。java
输入“Swashbuckle.core”web
引入到咱们的项目中。api
打开 项目中的“PhoneBookWebApiModule.cs”文件.服务器
建立一个方法“ConfigureSwaggerUi();”cookie
/// <summary> /// 配置SwaggerUi /// </summary> private void ConfigureSwaggerUi() { Configuration.Modules.AbpWebApi().HttpConfiguration .EnableSwagger(c => { c.SingleApiVersion("v1", "YoYoCMS.PhoneBookAPI文档"); c.ResolveConflictingActions(apiDescriptions => apiDescriptions.First()); }) .EnableSwaggerUi(); }
而后在Initialize()中对他进行调用。架构
运行项目,打开”/swagger/ui/index”路径app
获得的效果
到此呢,ABP实现SwaggerUI的功能已经算是能够了。可是咱们不能就这么知足了。还不够,为何呢。由于咱们还要讲咱们的注释显示出来。
这样其余开发人员看到了接口名称才能说叫作API文档嘛。
你们要特别注意:
这里生成的XML文档,必定要注意是application类库中的,不是webapi类型的
是application类库、application类库、application类库
首先咱们回到 方法:ConfigureSwaggerUi中,对他进行改造。
首先打开application类库的属性设置,而后在生成中找到XML文档文件,启用生成
而后再对ConfigureSwaggerUi方法进行改造
//将application层中的注释添加到SwaggerUI中 var baseDirectory = AppDomain.CurrentDomain.BaseDirectory; var commentsFileName = "Bin//YoYoCMS.PhoneBook.Application.xml"; var commentsFile = Path.Combine(baseDirectory, commentsFileName); //将注释的XML文档添加到SwaggerUI中 c.IncludeXmlComments(commentsFile);
添加如下到方法中。
而后运行项目:
咦。。。怎么没有。。注释呢。。。。
固然这一切的一切只是咱们能够加注释,来如今咱们把注释加上。。
而后再来运行一次项目。。。
上图咱们就能够看到了。已经获得了注释信息,之后开发不再怕哪一个接口是哪一个了。
到目前为止咱们访问SwaggerUI的方式都是”/swagger/ui/index/” 这样的路径访问方式。
我的感受不是很方面咱们对它进行稍微的优化下。
咱们能够看到EnableSwaggerUi,F12转到定义下。
支持路由重定向,那么咱们就开始改造吧。
其实就这么一句话,改造后的访问路径“/apis/index”就能够了。
看看效果。
这样操做接口就比较方便了。
.EnableSwaggerUi("apis/{*assetPath}", b => { b.InjectJavaScript(); b.InjectStylesheet(); });
一个 是注入JavaScript文件,一个是输入css文件。因此若是这里能够对咱们的SwaggerUI界面进行自定义修改的。
须要将js文件路径注入到SwaggerUI中。
.EnableSwaggerUi("apis/{*assetPath}", b => { //对js进行了拓展 b.InjectJavaScript(Assembly.GetExecutingAssembly(), "YoYoCMS.PhoneBook.SwaggerUi.scripts.swagger.js"); });
//YoYoCMS.PhoneBook.SwaggerUi.scripts.swagger.js是你的命名空间加上文件的路径.
YoYoCMS.PhoneBook 是你的项目默认命名空间
而后接下来才是你的各类文件夹结构。。
swagger.js须要设置为嵌入的资源。
请注意你的项目结构。每个.表明的是一个文件夹
swagger.js 也放出来。
'use strict'; /** * Translator for documentation pages. * * To enable translation you should include one of language-files in your index.html * after <script src='lang/translator.js' type='text/javascript'></script>. * For example - <script src='lang/ru.js' type='text/javascript'></script> * * If you wish to translate some new texsts you should do two things: * 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. * 2. Mark that text it templates this way <anyHtmlTag data-sw-translate>New Phrase</anyHtmlTag> or <anyHtmlTag data-sw-translate value='New Phrase'/>. * The main thing here is attribute data-sw-translate. Only inner html, title-attribute and value-attribute are going to translate. * */ 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'))); }); }, _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(); });
这两天有陆续看到留言说 提示使用动态请求的时候报错400
缘由是在1.0后ABP开启了一个功能”Cross-Site Request Forgery”CSRF 中文叫作跨站请求伪造
怎么搞定呢。
1种是在咱们的swaggerui的js中添加:
var getCookieValue = function(key) { var equalities = document.cookie.split('; '); for (var i = 0; i < equalities.length; i++) { if (!equalities[i]) { continue; } var splitted = equalities[i].split('='); if (splitted.length !== 2) { continue; } if (decodeURIComponent(splitted[0]) === key) { return decodeURIComponent(splitted[1] || ''); } } return null; }; var csrfCookie = getCookieValue("XSRF-TOKEN"); var csrfCookieAuth = new SwaggerClient.ApiKeyAuthorization("X-XSRF-TOKEN", csrfCookie, "header"); swaggerUi.api.clientAuthorizations.add("X-XSRF-TOKEN", csrfCookieAuth);
以上JavaScript代码。
还有一种是在webapimodule中关闭 CSRF功能
public override void PreInitialize() { ////关闭跨站脚本攻击 Configuration.Modules.AbpWeb().AntiForgery.IsEnabled = false; }
有小伙伴在群里问SwaggerUI这么强大,到了生产环境是否是要手动屏蔽?
刚刚通过个人实际测试发现无须担心这个问题。
当咱们把项目发布到IIS后。
再次打开SwaggerUI
就会发现报500错误,因此这个隐忧看看不用考虑了
若是你以为本文章对你有帮助,能够对我打赏哦。屏幕右方
群里能够下载源代码
交流QQ群: 104390185
如此。The End