ASP.NET Core 中文文檔 第二章 指南 (09) 使用 Swagger 生成 ASP.NET Web API 線上幫助測試文檔

来源:http://www.cnblogs.com/dotNETCoreSG/archive/2016/08/29/aspnetcore_02-09_web-api-help-pages-using-swagger.html
-Advertisement-
Play Games

對於開發人員來說,構建一個消費應用程式時去瞭解各種各樣的 API 是一個巨大的挑戰。 在你的 Web API 項目中使用 [Swagger](http://swagger.io/) 的 .NET Core 封裝 [Swashbuckle](https://github.com/domaindriv... ...


原文:ASP.NET Web API Help Pages using Swagger
作者:Shayne Boyer
翻譯:謝煬(kiler)
翻譯:許登洋(Seay)

對於開發人員來說,構建一個消費應用程式時去瞭解各種各樣的 API 是一個巨大的挑戰。

在你的 Web API 項目中使用 Swagger 的 .NET Core 封裝 Swashbuckle 可以幫助你創建良好的文檔和幫助頁面。 Swashbuckle 可以通過修改 Startup.cs 作為一組 NuGet 包方便的加入項目。

  • Swashbuckle 是一個開源項目,為使用 ASP.NET Core MVC 構建的 Web APIs 生成 Swagger 文檔。
  • Swagger 是一個機器可讀的 RESTful API 表現層,它可以支持互動式文檔、客戶端 SDK 的生成和可被髮現。

本教程基於 用 ASP.NET Core MVC 和 Visual Studio 創建你的第一個 Web API 文檔的例子構建。如果需要對應的代碼,在這裡 https://github.com/aspnet/Docs/tree/master/aspnet/tutorials/first-web-api/sample 下載示例。

開始入門

Swashbuckle 有兩個核心的組件

  • Swashbuckle.SwaggerGen : 提供生成描述對象、方法、返回類型等的 JSON Swagger 文檔的功能。
  • Swashbuckle.SwaggerUI : 是一個嵌入式版本的 Swagger UI 工具,使用 Swagger UI 強大的富文本表現形式來可定製化的來描述 Web API 的功能,並且包含內置的公共方法測試工具。

NuGet 包

你可以通過以下方式添加 Swashbuckle:

  • 通過 Package Manager 控制台:

    Install-Package Swashbuckle -Pre
  • 在 project.json 中添加 Swashbuckle:

    "Swashbuckle": "6.0.0-beta902"
  • 在 Visual Studio 中:
    • 右擊你的項目 Solution Explorer > Manage NuGet Packages
    • 在搜索框中輸入 Swashbuckle
    • 點擊 “Include prerelease”
    • 設置 Package source 為 nuget.org
    • 點擊 Swashbuckle 包並點擊 Install

在中間件中添加並配置 Swagger

在 Configure 方法裡面把 SwaggerGen 添加到 services 集合,並且在 ConfigureServices 方法中,允許中間件提供和服務生成 JSON 文檔以及 SwaggerUI。

  public void ConfigureServices(IServiceCollection services)
  {
      // Add framework services.
      services.AddMvc();

      services.AddLogging();

      // Add our repository type
      services.AddSingleton<ITodoRepository, TodoRepository>();

      // Inject an implementation of ISwaggerProvider with defaulted settings applied
      services.AddSwaggerGen();
  }

  // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
  public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
  {
      app.UseMvcWithDefaultRoute();

      // Enable middleware to serve generated Swagger as a JSON endpoint
      app.UseSwagger();

      // Enable middleware to serve swagger-ui assets (HTML, JS, CSS etc.)
      app.UseSwaggerUi();

  }

在 Visual Studio 中, 點擊 ^F5 啟動應用程式並導航到 http://localhost:<random_port>/swagger/v1/swagger.json 頁面可以看成生成的終端描述文檔。

提示
Microsoft Edge,Google Chrome 以及 Firefox 原生支持顯示 JSON 文檔。 Chrome 的擴展會格式化文檔使其更易於閱讀。 下麵的例子是簡化版的。

{
"swagger": "2.0",
"info": {
    "version": "v1",
    "title": "API V1"
},
"basePath": "/",
"paths": {
    "/api/Todo": {
    "get": {
        "tags": [
        "Todo"
        ],
        "operationId": "ApiTodoGet",
        "consumes": [],
        "produces": [
        "text/plain",
        "application/json",
        "text/json"
        ],
        "responses": {
        "200": {
            "description": "OK",
            "schema": {
            "type": "array",
            "items": {
                "$ref": "#/definitions/TodoItem"
            }
            }
        }
        },
        "deprecated": false
    },
    "post": {
        ...
    }
    },
    "/api/Todo/{id}": {
    "get": {
        ...
    },
    "put": {
        ...
    },
    "delete": {
        ...
},
"definitions": {
    "TodoItem": {
    "type": "object",
    "properties": {
        "key": {
        "type": "string"
        },
        "name": {
        "type": "string"
        },
        "isComplete": {
        "type": "boolean"
        }
    }
    }
},
"securityDefinitions": {}
}

這個文檔用來驅動 Swagger UI,可以通過訪問 http://localhost:<random_port>/swagger/ui 頁面來查看。
swagger-ui

所有的 ToDo controller 的方法都是可以在 UI 上面進行測試。點擊方法可以展開對應的區域,輸入所需的參數並且點擊 “Try it out!” 。
get-try-it-out

自定義與可擴展性

Swagger 不僅是顯示 API 的一個簡單方法,而且有可選項:文檔對象模型,以及自定義交互 UI 來滿足你的視覺感受或者設計語言。

API 信息和描述

ConfigureSwaggerGen 方法用來添加文檔信息。例如:作者,版權,描述。

services.ConfigureSwaggerGen(options =>
{
    options.SingleApiVersion(new Info
    {
        Version = "v1",
        Title = "ToDo API",
        Description = "A simple example ASP.NET Core Web API",
        TermsOfService = "None",
        Contact = new Contact { Name = "Shayne Boyer", Email = "", Url = "http://twitter.com/spboyer"},
        License = new License { Name = "Use under LICX", Url = "http://url.com" }
    });
});

下圖展示了 Swagger UI 顯示添加的版本信息。
custom-info

XML 註釋

為了啟用 XML 註釋, 在 Visual Studio 中右擊項目並且選擇 Properties 在 Output Settings 區域下麵點擊 XML Documentation file 。
swagger-xml-comments

另外,你也可以通過在 project.json 中設置 “xmlDoc”: true 來啟用 XML 註釋。

"buildOptions": {
    "emitEntryPoint": true,
    "preserveCompilationContext": true,
    "xmlDoc": true
},

配置 Swagger 使用生成的 XML 文件。

提示
對於 Linux 或者 非 Windows 操作系統,文件名和路徑是大小寫敏感的。 所以本例中的 ToDoApi.XML 在 Windows 上可以找到但是 CentOS 就無法找到。

// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{
    // Add framework services.
    services.AddMvc();

    services.AddLogging();

    // Add our repository type.
    services.AddSingleton<ITodoRepository, TodoRepository>();

    // Inject an implementation of ISwaggerProvider with defaulted settings applied.
    services.AddSwaggerGen();

    // Add the detail information for the API.
    services.ConfigureSwaggerGen(options =>
    {
        options.SingleApiVersion(new Info
        {
            Version = "v1",
            Title = "ToDo API",
            Description = "A simple example ASP.NET Core Web API",
            TermsOfService = "None",
            Contact = new Contact { Name = "Shayne Boyer", Email = "", Url = "http://twitter.com/spboyer"},
            License = new License { Name = "Use under LICX", Url = "http://url.com" }
        });

        //Determine base path for the application.
        var basePath = PlatformServices.Default.Application.ApplicationBasePath;

        //Set the comments path for the swagger json and ui.
        options.IncludeXmlComments(basePath + "\\TodoApi.xml");
    });
}

// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
{
    app.UseStaticFiles();

    app.UseMvcWithDefaultRoute();

    // Enable middleware to serve generated Swagger as a JSON endpoint.
    app.UseSwagger();

    // Enable middleware to serve swagger-ui assets (HTML, JS, CSS etc.)
    app.UseSwaggerUi();
    
}

在上面的代碼中,ApplicationBasePath 獲取到應用程式的根路徑,是需要設置 XML 註釋文件的完整路徑。 TodoApi.xml 僅適用於本例,生成的XML註釋文件的名稱是基於你的應用程式名稱。

為方法添加的三斜線註釋(C# 文檔註釋格式)文字會作為描述顯示在 Swagger UI 對應方法的頭區域。

/// <summary>
/// Deletes a specific TodoItem.
/// </summary>
/// <param name="id"></param>
[HttpDelete("{id}")]
public void Delete(string id)
{
    TodoItems.Remove(id);
}

triple-slash-comments

請註意,UI 是由生成的 JSON 文件驅動的,這些註釋也會包含在文件中。

  "delete": {
    "tags": [
      "Todo"
    ],
    "summary": "Deletes a specific TodoItem",
    "operationId": "ApiTodoByIdDelete",
    "consumes": [],
    "produces": [],
    "parameters": [
      {
        "name": "id",
        "in": "path",
        "description": "",
        "required": true,
        "type": "string"
      }
    ],
    "responses": {
      "204": {
        "description": "No Content"
      }
    },
    "deprecated": false
  }

這是一個更強大的例子,加入 <remarks /> 那裡面的內容可以是文字或添加的 JSON 或 XML 對象的方法為進一步描述方法文檔而服務。

/// <summary>
/// Creates a TodoItem.
/// </summary>
/// <remarks>
/// Note that the key is a GUID and not an integer.
///  
///     POST /Todo
///     {
///        "key": "0e7ad584-7788-4ab1-95a6-ca0a5b444cbb",
///        "name": "Item1",
///        "isComplete": true
///     }
/// 
/// </remarks>
/// <param name="item"></param>
/// <returns>New Created Todo Item</returns>
/// <response code="201">Returns the newly created item</response>
/// <response code="400">If the item is null</response>
[HttpPost]
[ProducesResponseType(typeof(TodoItem), 201)]
[ProducesResponseType(typeof(TodoItem), 400)]
public IActionResult Create([FromBody, Required] TodoItem item)
{
    if (item == null)
    {
        return BadRequest();
    }
    TodoItems.Add(item);
    return CreatedAtRoute("GetTodo", new { id = item.Key }, item);
}

請註意下麵是這些附加註釋的在用戶界面的增強效果。
xml-comments-extended

DataAnnotations

你可以使用 System.ComponentModel.DataAnnotations 來標註 API controller ,幫助驅動 Swagger UI 組件。

在 TodoItem 類的 Name 屬性上添加 [Required] 標註會改變 UI 中的模型架構信息。[Produces("application/json"] ,正則表達式驗證器將更進一步細化生成頁面傳遞的詳細信息。代碼中使用的元數據信息越多 API 幫助頁面上的描述信息也會越多。

using System;
using System.ComponentModel;
using System.ComponentModel.DataAnnotations;

namespace TodoApi.Models
{
    public class TodoItem
    {
        public string Key { get; set; }
        [Required]
        public string Name { get; set; }
        [DefaultValue(false)]
        public bool IsComplete { get; set; }
    }
}

描述響應類型

API 使用開發者最關心的東西是的返回結果;具體響應類型,錯誤代碼(如果不是標準錯誤碼)。這些都在 XML 註釋 和 DataAnnotations 中處理。

以 Create() 方法為例,目前它僅僅返回 “201 Created” 預設響應。如果數據實際創建了或者 POST 正文沒有傳遞數據返回 “204 No Content” 錯誤,這是理所當然的。但是,如果沒有文檔知道它的存在或者存在任何其他響應,則可以通過添加下麵的代碼段是修複這個問題。

/// <summary>
/// Creates a TodoItem.
/// </summary>
/// <remarks>
/// Note that the key is a GUID and not an integer.
///  
///     POST /Todo
///     {
///        "key": "0e7ad584-7788-4ab1-95a6-ca0a5b444cbb",
///        "name": "Item1",
///        "isComplete": true
///     }
/// 
/// </remarks>
/// <param name="item"></param>
/// <returns>New Created Todo Item</returns>
/// <response code="201">Returns the newly created item</response>
/// <response code="400">If the item is null</response>
[HttpPost]
[ProducesResponseType(typeof(TodoItem), 201)]
[ProducesResponseType(typeof(TodoItem), 400)]
public IActionResult Create([FromBody, Required] TodoItem item)
{
    if (item == null)
    {
        return BadRequest();
    }
    TodoItems.Add(item);
    return CreatedAtRoute("GetTodo", new { id = item.Key }, item);
}

data-annotations-response-types

自定義 UI

stock UI 是一個非常實用的展示方案,如果你想在生成 API 文檔頁面的時候想把你的標題做的更好看點。

完成與 Swashbuckle 組件相關的任務很簡單,但服務需要添加的資源來通常不會被包含在 Web API 項目中,所以必須建立對應的的文件夾結構來承載這些靜態資源文件。

在項目中添加 "Microsoft.AspNetCore.StaticFiles": "1.0.0-*" NuGet 包。

在中間件中啟用 static files 服務。

// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
{
    app.UseStaticFiles();

    app.UseMvcWithDefaultRoute();

    // Enable middleware to serve generated Swagger as a JSON endpoint
    app.UseSwagger();

    // Enable middleware to serve swagger-ui assets (HTML, JS, CSS etc.)
    app.UseSwaggerUi();

}

從 Github repository 上獲取 Swagger UI 頁面所需的 index.html 核心文件,把他放到 wwwroot/swagger/ui 目錄下,併在在同一個文件夾創建一個新的 custom.css 文件。

custom-files-folder-view

在 index.html 文件中引用 custom.css 。

<link href='custom.css' media='screen' rel='stylesheet' type='text/css' />

下麵的 CSS 提供了一個自定義頁面標題的簡單的示例。

custom.css 文件

.swagger-section #header
{
    border-bottom: 1px solid #000000;
    font-style: normal;
    font-weight: 400;
    font-family: "Segoe UI Light","Segoe WP Light","Segoe UI","Segoe WP",Tahoma,Arial,sans-serif;
    background-color: black;
}

.swagger-section #header h1
{
    text-align: center;
    font-size: 20px;
    color: white;
}

index.html 正文

<body class="swagger-section">
   <div id="header">
    <h1>ToDo API Documentation</h1>
   </div>

   <div id="message-bar" class="swagger-ui-wrap" data-sw-translate>&nbsp;</div>
   <div id="swagger-ui-container" class="swagger-ui-wrap"></div>
</body>

custom-header

你可以在這個頁面有更多改進的東西,請在 Swagger UI Github repository 參閱完整的 UI 資源。

返回目錄


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

-Advertisement-
Play Games
更多相關文章
  • ...
  • ...
  • 本文為七小站主原創作品,轉載請註明出處:http://www.cnblogs.com/qixiaoyizhan/ ...
  • 一.NPOI 函式庫: NPOI 函式庫檔案有七個,NPOI 函式庫可以在 http://npoi.codeplex.com 中下載,分別是: NPOI.DLL:NPOI 核心函式庫。 NPOI.DDF.DLL:NPOI 繪圖區讀寫函式庫。 NPOI.HPSF.DLL:NPOI 文件摘要資訊讀寫函式 ...
  • EF to MySql一般都是用using最後Commit,一直以為最後沒Commit,當using調用Dispose會自動Rollback,沒想到這兒有個坑,mysql有個bug並不會Rollback,事務也不會關閉,所以再次BeginTransaction就會報An error occurred ...
  • Linq To Objects - 如何操作文件目錄 開篇語: 上次發佈的 《LINQ:進階 - LINQ 標準查詢操作概述》 社會反響不錯,但自己卻始終覺得缺點什麼!“紙上得來終覺淺,絕知此事要躬行”,沒錯,就是實戰!這次讓我們一起來看看一些操作文件目錄的技巧,也許能引我們從不同的角度思考問題,從 ...
  • 最前面的話:Smobiler是一個在VS環境中使用.Net語言來開發APP的開發平臺,也許比Xamarin更方便 ...
  • 因為公司現在存在.net站點和asp站點共同運行的情況,所以需要對IIS進行一些修改,運行環境Win2003+IIS6 一、起因 原來的老站是asp開發的,用的是.net 2.0運行環境; 新站是.net開發的,用的是.net 4.0運行環境; 所以需要對配置的站點進行.net Framework的 ...
一周排行
    -Advertisement-
    Play Games
  • 前言 微服務架構已經成為搭建高效、可擴展系統的關鍵技術之一,然而,現有許多微服務框架往往過於複雜,使得我們普通開發者難以快速上手並體驗到微服務帶了的便利。為瞭解決這一問題,於是作者精心打造了一款最接地氣的 .NET 微服務框架,幫助我們輕鬆構建和管理微服務應用。 本框架不僅支持 Consul 服務註 ...
  • 先看一下效果吧: 如果不會寫動畫或者懶得寫動畫,就直接交給Blend來做吧; 其實Blend操作起來很簡單,有點類似於在操作PS,我們只需要設置關鍵幀,滑鼠點來點去就可以了,Blend會自動幫我們生成我們想要的動畫效果. 第一步:要創建一個空的WPF項目 第二步:右鍵我們的項目,在最下方有一個,在B ...
  • Prism:框架介紹與安裝 什麼是Prism? Prism是一個用於在 WPF、Xamarin Form、Uno 平臺和 WinUI 中構建鬆散耦合、可維護和可測試的 XAML 應用程式框架 Github https://github.com/PrismLibrary/Prism NuGet htt ...
  • 在WPF中,屏幕上的所有內容,都是通過畫筆(Brush)畫上去的。如按鈕的背景色,邊框,文本框的前景和形狀填充。藉助畫筆,可以繪製頁面上的所有UI對象。不同畫筆具有不同類型的輸出( 如:某些畫筆使用純色繪製區域,其他畫筆使用漸變、圖案、圖像或繪圖)。 ...
  • 前言 嗨,大家好!推薦一個基於 .NET 8 的高併發微服務電商系統,涵蓋了商品、訂單、會員、服務、財務等50多種實用功能。 項目不僅使用了 .NET 8 的最新特性,還集成了AutoFac、DotLiquid、HangFire、Nlog、Jwt、LayUIAdmin、SqlSugar、MySQL、 ...
  • 本文主要介紹攝像頭(相機)如何採集數據,用於類似攝像頭本地顯示軟體,以及流媒體數據傳輸場景如傳屏、視訊會議等。 攝像頭採集有多種方案,如AForge.NET、WPFMediaKit、OpenCvSharp、EmguCv、DirectShow.NET、MediaCaptre(UWP),網上一些文章以及 ...
  • 前言 Seal-Report 是一款.NET 開源報表工具,擁有 1.4K Star。它提供了一個完整的框架,使用 C# 編寫,最新的版本採用的是 .NET 8.0 。 它能夠高效地從各種資料庫或 NoSQL 數據源生成日常報表,並支持執行複雜的報表任務。 其簡單易用的安裝過程和直觀的設計界面,我們 ...
  • 背景需求: 系統需要對接到XXX官方的API,但因此官方對接以及管理都十分嚴格。而本人部門的系統中包含諸多子系統,系統間為了穩定,程式間多數固定Token+特殊驗證進行調用,且後期還要提供給其他兄弟部門系統共同調用。 原則上:每套系統都必須單獨接入到官方,但官方的接入複雜,還要官方指定機構認證的證書 ...
  • 本文介紹下電腦設備關機的情況下如何通過網路喚醒設備,之前電源S狀態 電腦Power電源狀態- 唐宋元明清2188 - 博客園 (cnblogs.com) 有介紹過遠程喚醒設備,後面這倆天瞭解多了點所以單獨加個隨筆 設備關機的情況下,使用網路喚醒的前提條件: 1. 被喚醒設備需要支持這WakeOnL ...
  • 前言 大家好,推薦一個.NET 8.0 為核心,結合前端 Vue 框架,實現了前後端完全分離的設計理念。它不僅提供了強大的基礎功能支持,如許可權管理、代碼生成器等,還通過採用主流技術和最佳實踐,顯著降低了開發難度,加快了項目交付速度。 如果你需要一個高效的開發解決方案,本框架能幫助大家輕鬆應對挑戰,實 ...