ABP教程-給項目添加SwaggerUI,生成動態webapi


上一篇,我們是正式將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();
});

 

* 關於新版的ABP繼續翻船的地方

這兩天有陸續看到留言說 提示使用動態請求的時候報錯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;



           

           
        }

 

6、最終運行的效果

image

SwaggerUI在生產環境的隱憂

有小伙伴在群里問SwaggerUI這么強大,到了生產環境是不是要手動屏蔽?

剛剛經過我的實際測試發現無須擔憂這個問題。

當我們把項目發布到IIS后。

image

再次打開SwaggerUI

image

就會發現報500錯誤,所以這個隱憂看看不用考慮了

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

群里可以下載源代碼

交流QQ群: 104390185

如此。The End

-返回目錄-  ABP打造一個《電話簿項目》


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM