Swagger 一個建立 Web API 文件的好工具,它可以網站裡直接產生 API 的文件頁面,且可直接在上面測試 API。

目前支援 ASP.NET Core 中的 library,試了幾個,NSwag 算是目前設定上比較簡單的,而它產生出來的頁面如下:

首先在 NuGet 搜尋 NSwag.AspNetCore 並安裝,然後在 Startup.cs 加入下列設定:

public void ConfigureServices(IServiceCollection services)
{
........
    services.AddSwaggerDocument();
}

public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
........
    app.UseSwaggerUi3();
........
}

最後從網址 https://[FQDN]/swagger/index.html 進去,就可以看到頁面了。需要注意的是,如果 Controller 不是 Web API,而是具有 View 功能的 Controller,需加入一些設定,例如下列 Controller:

/// <summary>
/// example
/// </summary>
[Route("example")]
public class ExampleController : Controller
{
    /// <summary>
    /// example API
    /// </summary>
    /// <returns>json result object</returns>
    [HttpGet("Index")]
    public IActionResult Index()
    {
        TestModel model = new TestModel
        {
            Field1 = "aaa3",
            Field2 = "aaa4"
        };
        return new JsonResult(model);
    }
}

類別上需明確加入 [Route("example")] 這類的 attribute,而 action 上也要指定 http method 及 route 路徑。

參考資料