使用ABP實現SwaggerUI,生成動態webapi

文章轉載:http://www.cnblogs.com/wer-ltm/p/5776024.html


上一篇,我們是正式將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錯誤,所以這個隱憂看看不用考慮了

如果你覺得本文章對你有幫助,可以對我打賞哦。屏幕右方

羣裏可以下載源代碼

交流QQ羣:

如此。The End

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章