[Swagger] 如何在 ASP․NET Core 使用 Swagger - Swashbuckle

  • 2312
  • 0

透過 Swashbuckle 套件,將 Swagger 加入 ASP.NET Core 3.1 Web API 專案中
 

1. Install the NuGet Package

Install-Package Swashbuckle.AspNetCore

After install successfully, you can see this in Packages.

2. Register swagger generator service at Startup

Use Ctrl+T go to Startup.cs file and then use Alt+\ go to ConfigureServices method.
Add below code : 

// Register the Swagger Generator service.
// This service is responsible for genrating Swagger Documents.
services.AddSwaggerGen(config =>
{
    config.SwaggerDoc("v1", new OpenApiInfo
    {
        Version = "v1",
        Title = "API Document",
        Description = "API Document For Xinyi LineChatBot",
        Contact = new OpenApiContact
        {
            Name = "Xinyi Kao",
            Email = string.Empty
        }
    });
});

Note: Add this AddSwaggerGen() method after AddMvc() or AddMvcCore().

 

3. Add swagger middleware and swaggerUI

Use Alt+\ go to Configure method.
Add below code : 

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

// Enable middleware to serve swagger-ui (HTML, JS, CSS, etc.),
// specifying the Swagger JSON endpoint.
app.UseSwaggerUI(c =>
{
    c.SwaggerEndpoint("/api/swagger/v1/swagger.json", "API Document V1");
});

4. Open swagger.

Open swagger https://localhost:{Port_Number}/swagger/index.html
Can see this page.

5. Open swagger in other link you want.

If you want to change open Swagger UI link like https://localhost:{Port_Number}/api/swagger/index.html
Can add this.

// Enable middleware to serve generated Swagger as a JSON endpoint.
app.UseSwagger(c =>
{
    c.RouteTemplate = "/api/swagger/{documentName}/swagger.json";
});

// Enable middleware to serve swagger-ui (HTML, JS, CSS, etc.),
// specifying the Swagger JSON endpoint.
app.UseSwaggerUI(c =>
{
    c.SwaggerEndpoint("/api/swagger/v1/swagger.json", "API Document V1");
    c.RoutePrefix = "api/swagger";
});

參考:

Swashbuckle 與 ASP.NET Core 使用者入門

Adding Swagger to ASP.NET Core 3.1 Web API

Swagger 與 OpenAPI 相關名次解釋與介紹:

如何在 ASP․NET Core 3 完整設定 NSwag 與 OpenAPI v3 文件