c# webapi結合swagger的使用

来源:https://www.cnblogs.com/htsboke/archive/2019/09/06/11475681.html
-Advertisement-
Play Games

一、使用nuget下載swagger包 Install-Package Swashbuckle 二、配置swagger 1. 安裝完Swashbuckle後,nuget會將相關引用添加至WebApi項目,其中會在App_Start文件夾下添加一個SwaggerConfig.cs文件,如下圖所示: 2 ...


一、使用nuget下載swagger包

     Install-Package Swashbuckle

 

二、配置swagger

    1. 安裝完Swashbuckle後,nuget會將相關引用添加至WebApi項目,其中會在App_Start文件夾下添加一個SwaggerConfig.cs文件,如下圖所示:
     

 

   2. 設置WebApi生成時,順便生成一份xml文檔信息,用於swagger使用

   

 

  3. 配置swagger引用項目類庫生成的xml文檔,在SwaggerConfig.cs文件裡面進行配置

 

 

 

 

  4. 漢化swaggerui

'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();
});
swagger_lang_cn.js

  註意修改漢化的js文件屬性的“生成操作”改為:“嵌入的資源

配置swagger註入漢化文件

 

 

 

 

  

三、配置swagger代碼

 

 /// <summary>
    /// swagger文檔配置信息
    /// </summary>
    public class SwaggerConfig
    {
        /// <summary>
        /// 註冊swagger相關配置信息
        /// </summary>
        public static void Register()
        {
            var thisAssembly = typeof(SwaggerConfig).Assembly;

            GlobalConfiguration.Configuration
                .EnableSwagger(c =>
                    {
                        //設置swagger顯示的版本號和標題
                        c.SingleApiVersion("v1", "Api描述文檔");

                        //設置介面描述xml路徑地址
                        var webApiXmlPath = string.Format("{0}/bin/ClearSite.WebApi.xml", System.AppDomain.CurrentDomain.BaseDirectory);
                        c.IncludeXmlComments(webApiXmlPath);

                        //設置介面描述xml路徑地址
                        var applicationXmlPath = string.Format("{0}/bin/ClearSite.Application.xml", System.AppDomain.CurrentDomain.BaseDirectory);
                        c.IncludeXmlComments(applicationXmlPath);

                        //設置介面描述xml路徑地址
                        var coreXmlPath = string.Format("{0}/bin/ClearSite.Core.xml", System.AppDomain.CurrentDomain.BaseDirectory);
                        c.IncludeXmlComments(coreXmlPath);

                        //添加操作選項
                        //c.OperationFilter<AuthTokenHeaderParameter>();
                    })
                .EnableSwaggerUi(c =>
                    {
                        //載入漢化的js文件,註意 swagger_lang_cn.js 文件屬性必須設置為“嵌入的資源”。
                        c.InjectJavaScript(System.Reflection.Assembly.GetExecutingAssembly(), "ClearSite.WebApi.Scripts.swagger_lang_cn.js");
                    });
        }
    }
SwaggerConfig.cs

 

 

 

四、運行結果

 

 

 

 

 

  

 


您的分享是我們最大的動力!

-Advertisement-
Play Games
更多相關文章
  • websocket消息服務 目的:搭建websocket服務,用瀏覽器與服務進行消息交互(寫的第一個Go程式) 代碼目錄結構: 前端html頁面: 1 <!DOCTYPE html> 2 <html> 3 <head> 4 <meta charset="utf-8"> 5 <script> 6 wi ...
  • 題目描述: 給定兩個整數 a, b (a, b 均不超過 int 類型的表示範圍),求出 a + b 的和。輸入描述: 多組輸入,每組輸入為一行,裡面有 2 個數 a, b。輸出描述: 對於每一組輸入,輸出一個值為該組 a + b 的和。樣例輸入: 1 2 2 3樣例輸出: 3 5 ...
  • Linux系統大多數都支持OpenSSH,生成公鑰、私鑰的最好用ssh-keygen命令,如果用putty自帶的PUTTYGEN.EXE生成會不相容OpenSSH,從而會導致登錄時出現server refused our key錯誤。 ...
  • 繼承 什麼是繼承?就是一個派生類(derived class)繼承基類(base class)的欄位和方法。一個類可以被多個類繼承;在python中,一個類可以繼承多個類。 父類可以稱為基類和超類,而子類可以稱為派生類 在繼承中可分為單繼承和多繼承兩種 下麵是繼承的用法,語法為'class 子類的名 ...
  • 參考鏈接:https://www.cnblogs.com/taiyonghai/p/5604159.html 類: /******************************************************************************************* ...
  • 部分一 14年底進入目前公司時,領導準備開發一款新軟體平臺以取代原有平臺。原平臺採用C++Build開發界面(window c/s客戶端) 、Visual Studio(封裝dll模塊)。過完年,領導已把框架搭建完畢(過年期間領導加班了 ^_^ )。當時菜鳥一個(目前老鳥了),新框架用wpf模式,R ...
  • 前提 入行已經7,8年了,一直想做一套漂亮點的自定義控制項,於是就有了本系列文章。 GitHub:https://github.com/kwwwvagaa/NetWinformControl 碼雲:https://gitee.com/kwwwvagaa/net_winform_custom_contr ...
  • 前提 入行已經7,8年了,一直想做一套漂亮點的自定義控制項,於是就有了本系列文章。 GitHub:https://github.com/kwwwvagaa/NetWinformControl 碼雲:https://gitee.com/kwwwvagaa/net_winform_custom_contr ...
一周排行
    -Advertisement-
    Play Games
  • 移動開發(一):使用.NET MAUI開發第一個安卓APP 對於工作多年的C#程式員來說,近來想嘗試開發一款安卓APP,考慮了很久最終選擇使用.NET MAUI這個微軟官方的框架來嘗試體驗開發安卓APP,畢竟是使用Visual Studio開發工具,使用起來也比較的順手,結合微軟官方的教程進行了安卓 ...
  • 前言 QuestPDF 是一個開源 .NET 庫,用於生成 PDF 文檔。使用了C# Fluent API方式可簡化開發、減少錯誤並提高工作效率。利用它可以輕鬆生成 PDF 報告、發票、導出文件等。 項目介紹 QuestPDF 是一個革命性的開源 .NET 庫,它徹底改變了我們生成 PDF 文檔的方 ...
  • 項目地址 項目後端地址: https://github.com/ZyPLJ/ZYTteeHole 項目前端頁面地址: ZyPLJ/TreeHoleVue (github.com) https://github.com/ZyPLJ/TreeHoleVue 目前項目測試訪問地址: http://tree ...
  • 話不多說,直接開乾 一.下載 1.官方鏈接下載: https://www.microsoft.com/zh-cn/sql-server/sql-server-downloads 2.在下載目錄中找到下麵這個小的安裝包 SQL2022-SSEI-Dev.exe,運行開始下載SQL server; 二. ...
  • 前言 隨著物聯網(IoT)技術的迅猛發展,MQTT(消息隊列遙測傳輸)協議憑藉其輕量級和高效性,已成為眾多物聯網應用的首選通信標準。 MQTTnet 作為一個高性能的 .NET 開源庫,為 .NET 平臺上的 MQTT 客戶端與伺服器開發提供了強大的支持。 本文將全面介紹 MQTTnet 的核心功能 ...
  • Serilog支持多種接收器用於日誌存儲,增強器用於添加屬性,LogContext管理動態屬性,支持多種輸出格式包括純文本、JSON及ExpressionTemplate。還提供了自定義格式化選項,適用於不同需求。 ...
  • 目錄簡介獲取 HTML 文檔解析 HTML 文檔測試參考文章 簡介 動態內容網站使用 JavaScript 腳本動態檢索和渲染數據,爬取信息時需要模擬瀏覽器行為,否則獲取到的源碼基本是空的。 本文使用的爬取步驟如下: 使用 Selenium 獲取渲染後的 HTML 文檔 使用 HtmlAgility ...
  • 1.前言 什麼是熱更新 游戲或者軟體更新時,無需重新下載客戶端進行安裝,而是在應用程式啟動的情況下,在內部進行資源或者代碼更新 Unity目前常用熱更新解決方案 HybridCLR,Xlua,ILRuntime等 Unity目前常用資源管理解決方案 AssetBundles,Addressable, ...
  • 本文章主要是在C# ASP.NET Core Web API框架實現向手機發送驗證碼簡訊功能。這裡我選擇是一個互億無線簡訊驗證碼平臺,其實像阿裡雲,騰訊雲上面也可以。 首先我們先去 互億無線 https://www.ihuyi.com/api/sms.html 去註冊一個賬號 註冊完成賬號後,它會送 ...
  • 通過以下方式可以高效,並保證數據同步的可靠性 1.API設計 使用RESTful設計,確保API端點明確,並使用適當的HTTP方法(如POST用於創建,PUT用於更新)。 設計清晰的請求和響應模型,以確保客戶端能夠理解預期格式。 2.數據驗證 在伺服器端進行嚴格的數據驗證,確保接收到的數據符合預期格 ...