透過 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.
![](https://dotblogsfile.blob.core.windows.net/user/xinxin/acb37ca4-72de-40ba-aa74-b1261a1106dd/1625401988.png)
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().
![](https://dotblogsfile.blob.core.windows.net/user/xinxin/acb37ca4-72de-40ba-aa74-b1261a1106dd/1625402143.png)
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");
});
![](https://dotblogsfile.blob.core.windows.net/user/xinxin/acb37ca4-72de-40ba-aa74-b1261a1106dd/1625402051.png)
4. Open swagger.
Open swagger https://localhost:{Port_Number}/swagger/index.html
Can see this page.
![](https://dotblogsfile.blob.core.windows.net/user/xinxin/acb37ca4-72de-40ba-aa74-b1261a1106dd/1625402349.png)
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";
});
![](https://dotblogsfile.blob.core.windows.net/user/xinxin/acb37ca4-72de-40ba-aa74-b1261a1106dd/1625402436.png)
參考:
Swashbuckle 與 ASP.NET Core 使用者入門
Adding Swagger to ASP.NET Core 3.1 Web API
Swagger 與 OpenAPI 相關名次解釋與介紹: