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


對於構建一個消費應用程序,理解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響應代碼:

 


免責聲明!

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



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