使用ABP实现SwaggerUI,生成动态webapi

来源:互联网 发布:淘宝买港版note7怎么退 编辑:程序博客网 时间:2024/06/05 11:36

上一篇,我们是正式将ABP生成的代码项目,跑起来了,然后演示了下多租户的不同。那么这篇我们就来实现下SwaggerUI。

Q:SwaggerUI是干什么的呢?

A:他是一个能将我们的webapi,通过Swagger Api来生成一个交互式的文档。通过他可以对你的接口进行调式。

1、引入Swashbuckle.core

选择PhoneBook.WebApi,然后添加nuget包(当然你也可以通过命令行添加)。

输入“Swashbuckle.core

image

引入到我们的项目中。

打开 项目中的“PhoneBookWebApiModule.cs”文件.

创建一个方法“ConfigureSwaggerUi();”

复制代码
/// <summary>        /// 配置SwaggerUi        /// </summary>        private void ConfigureSwaggerUi()        {            Configuration.Modules.AbpWebApi().HttpConfiguration                .EnableSwagger(c =>                {                    c.SingleApiVersion("v1", "YoYoCMS.PhoneBookAPI文档");                    c.ResolveConflictingActions(apiDescriptions => apiDescriptions.First());                })                .EnableSwaggerUi();        }
复制代码

然后在Initialize()中对他进行调用。

image

 

2、运行项目

运行项目,打开”/swagger/ui/index”路径

得到的效果

image

到此呢,ABP实现SwaggerUI的功能已经算是可以了。但是我们不能就这么满足了。还不够,为什么呢。因为我们还要讲我们的注释显示出来。

这样其他开发人员看到了接口名称才能说叫做API文档嘛。

3、对API文档进行增强

大家要特别注意:

这里生成的XML文档,一定要注意是application类库中的,不是webapi类型的

application类库、application类库、application类库

重要的事情重复三次。( 觉得好的右边求打赏  W03[IU_F_41WH6U9QZ7]J`H

首先我们回到 方法:ConfigureSwaggerUi中,对他进行改造。

首先打开application类库的属性设置,然后在生成中找到XML文档文件,启用生成

image

然后再对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);
复制代码

添加以下到方法中。

image

然后运行项目:

image

咦。。。怎么没有。。注释呢。。。。

CRC36P@9S3V{}Y]7TEQ]]70

当然这一切的一切只是我们可以加注释,来现在我们把注释加上。。E{OBPTRZT4[8IQFV8$@LQ3X

image

image

 

然后再来运行一次项目。。。

image

上图我们就可以看到了。已经得到了注释信息,以后开发再也不怕哪个接口是哪个了。

4、修改访问方式

到目前为止我们访问SwaggerUI的方式都是”/swagger/ui/index/” 这样的路径访问方式。

个人感觉不是很方面我们对它进行稍微的优化下。

我们可以看到EnableSwaggerUi,F12转到定义下。

image

image

支持路由重定向,那么我们就开始改造吧。

image

其实就这么一句话,改造后的访问路径“/apis/index”就可以了。

J5_ULNEP~{PT({XDIR{O~BS

看看效果。

image

这样操作接口就比较方便了。

5、进行将提示语言修改为中文

.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 是你的项目默认命名空间

image

然后接下来才是你的各种文件夹结构。。

image

swagger.js需要设置为嵌入的资源。

image

请注意你的项目结构。每一个.代表的是一个文件夹

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();});
复制代码

 

6、最终运行的效果

image

SwaggerUI在生产环境的隐忧

有小伙伴在群里问SwaggerUI这么强大,到了生产环境是不是要手动屏蔽?

刚刚经过我的实际测试发现无须担忧这个问题。

当我们把项目发布到IIS后。

image

再次打开SwaggerUI

image

就会发现报500错误,所以这个隐忧看看不用考虑了


转载地址:http://www.cnblogs.com/wer-ltm/p/5776024.html

0 0