使用Swagger來產生asp.net core Web API 文檔

來源:互聯網
上載者:User

標籤:檔案的   技術   val   desc   mail   script   命名   簡單的   mvc   

對於構建一個消費應用程式,理解API的各個方法對開發這是一個不小的挑戰。為了使你的API更利於閱讀。
使用Swagger為你的Web API產生好的文檔和協助頁,.NET Core實現了Swashbuckle.AspNetCore,使用Swagger是非常簡單的,只需添加一組Nuget包和修改Startup就可以搞定。

.Swashbuckle.AspNetCore 開源項目, ASP.NET Core Web API產生Swagger文檔的

.Swagger是一個機器可讀的restful風格的api介面的代表。他可以支援文檔互動用戶端sdk產生,並且具有可見度

1、入門

三個主要組件:

Swashbuck.AspNetCore.Swagger:Swagger物件模型和中介軟體,作為JSON終結點公開SwaggerDocument對象。

Swashbuckle.AspNetCore.SwaggerGen:一個Swagger產生器,可以直接從路由、控制器、模型構建SwaggerDocument對象。他通常和Swagger終結點中介軟體結合,以自動公開SwaggerJson

Swashbuckle.AspNetCore.SwaggerUI:Swagger UI工具的嵌入式版本,Swagger UI工具的嵌入式版本,它將Swagger JSON解釋為構建豐富的,可定製的Web API功能描述體驗。 它包括公用方法的內建測試線束。

2、通過下面命令安裝這三個組件

可以使用下面方法添加Swashbuckle

Install-Package Swashbuckle.AspNetCore

3、添加並配置到Swagger到中介軟體

將Swagger產生器添加到Startup.cs的ConfigureServices方法中。

public void ConfigureServices(IServiceCollection services){    services.AddDbContext<TodoContext>(opt => opt.UseInMemoryDatabase("TodoList"));    services.AddMvc();    //註冊Swagger產生器,定義一個和多個Swagger 文檔    services.AddSwaggerGen(c =>    {        c.SwaggerDoc("v1", new Info { Title = "My API", Version = "v1" });    });}

Info類包含在Swashbuckle.AspNetCore.Swagger命名空間中。

在Startup.cs類的Configure方法中。啟用中介軟體服務,主要產生JSON文檔和SwaggerUI.

public void Configure(IApplicationBuilder app){    //啟用中介軟體服務產生Swagger作為JSON終結點    app.UseSwagger();    //啟用中介軟體服務對swagger-ui,指定Swagger JSON終結點    app.UseSwaggerUI(c =>    {        c.SwaggerEndpoint("/swagger/v1/swagger.json", "My API V1");    });    app.UseMvc();}

  

啟動App,導航到http://localhost:<random_port>/swagger/v1/swagger.json ,顯示描述終結點的文檔。

可以通過瀏覽http://localhost:<random_port>/swagger來查看產生的Swagger UI。

 

 

 

TodoController中的每個公用操作方法都可以從UI進行測試。單擊一個方法名稱可以展開節點。添加參數,單機"測試"!

4、定製和可擴充性

Swagger提供了用於記錄物件模型和自訂UI。

API Info and Description

通過將一些資訊傳遞給AddSwaggerGen方法,如author、license和description

services.AddSwaggerGen(c =>{    c.SwaggerDoc("v1", 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 = "https://twitter.com/spboyer" },        License = new License { Name = "Use under LICX", Url = "https://example.com/license" }    });});

下面圖片描述了Swagger UI顯示的版本資訊

XML 注釋

啟用XML注釋


配置Swagger,讓Swagger使用產生的XML檔案。對於Linux和非Window作業系統,檔案名稱和路徑可以區分大小寫。

public void ConfigureServices(IServiceCollection services){    services.AddDbContext<TodoContext>(opt => opt.UseInMemoryDatabase("TodoList"));    services.AddMvc();    // Register the Swagger generator, defining one or more Swagger documents    services.AddSwaggerGen(c =>    {        c.SwaggerDoc("v1", 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 = "https://twitter.com/spboyer" },            License = new License { Name = "Use under LICX", Url = "https://example.com/license" }        });        // Set the comments path for the Swagger JSON and UI.        var basePath = PlatformServices.Default.Application.ApplicationBasePath;        var xmlPath = Path.Combine(basePath, "TodoApi.xml");         c.IncludeXmlComments(xmlPath);                    });}

在前面的代碼中,AppicationBasePath擷取應用程式的基本了路徑。用來尋找XML注釋檔案.TodoApi.xml僅適用於此樣本中,引文產生的XML注釋檔案的名稱基於應用程式的名稱。

像下面方法添加註釋

/// <summary>/// Deletes a specific TodoItem./// </summary>/// <param name="id"></param>        [HttpDelete("{id}")]public IActionResult Delete(long id){    var todo = _context.TodoItems.FirstOrDefault(t => t.Id == id);    if (todo == null)    {        return NotFound();    }    _context.TodoItems.Remove(todo);    _context.SaveChanges();    return new NoContentResult();}

在Create方法中添加下面注釋

/// <summary>/// Creates a TodoItem./// </summary>/// <remarks>/// Sample request://////     POST /Todo///     {///        "id": 1,///        "name": "Item1",///        "isComplete": true///     }////// </remarks>/// <param name="item"></param>/// <returns>A newly-created TodoItem</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] TodoItem item){    if (item == null)    {        return BadRequest();    }    _context.TodoItems.Add(item);    _context.SaveChanges();    return CreatedAtRoute("GetTodo", new { id = item.Id }, item);}

 Data Annotations

使用System.ComponentModel.DataAnnotations中的屬性裝飾模型,以協助驅動Swagger UI組件。

將[Required]屬性添加到TodoItem類的Name屬性中:

using System.ComponentModel;using System.ComponentModel.DataAnnotations;namespace TodoApi.Models{    public class TodoItem    {        public long Id { get; set; }        [Required]        public string Name { get; set; }        [DefaultValue(false)]        public bool IsComplete { get; set; }    }}

此屬性會更改UI行為並更改基礎JSON模式:

"definitions": {    "TodoItem": {        "required": [            "name"        ],        "type": "object",        "properties": {            "id": {                "format": "int64",                "type": "integer"            },            "name": {                "type": "string"            },            "isComplete": {                "default": false,                "type": "boolean"            }        }    }},

將[Produces("application/json")]屬性添加到API控制器。其目的是聲明控制器傳回型別支援application/json.

namespace TodoApi.Controllers{    [Produces("application/json")]    [Route("api/[controller]")]    public class TodoController : Controller    {        private readonly TodoContext _context;

隨著Web API中資料註解的使用量的增加,UI和API協助頁面變得更具描述性和實用性。

聲明響應類型

使用API的人員最關心的是返回什麼。特別是響應類型和錯誤碼
當請求為null時,Create 操作返回201建立成功和400 bad request.如果在Swagger UI中沒有合適的文檔。消費者就不瞭解這些結果。通過添加下面注釋類解決

/// <summary>/// Creates a TodoItem./// </summary>/// <remarks>/// Sample request://////     POST /Todo///     {///        "id": 1,///        "name": "Item1",///        "isComplete": true///     }////// </remarks>/// <param name="item"></param>/// <returns>A newly-created TodoItem</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] TodoItem item){    if (item == null)    {        return BadRequest();    }    _context.TodoItems.Add(item);    _context.SaveChanges();    return CreatedAtRoute("GetTodo", new { id = item.Id }, item);}

Swagger UI現在清楚地記錄了預期的HTTP響應代碼:

 

使用Swagger來產生asp.net core Web API 文檔

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.