Kích hoạt tài liệu XML trong dự án
Để Swagger có thể hiển thị đầy đủ chú thích cho các Model và Controller, cần cấu hình project file để sinh ra file XML khi build. Thêm các thuộc tính sau vào file .csproj:
<PropertyGroup>
<GenerateDocumentationFile>True</GenerateDocumentationFile>
<NoWarn>$(NoWarn);1591</NoWarn>
</PropertyGroup>
Cài đặt các gói NuGet cần thiết
Dự án cần cài đặt các package sau để hỗ trợ giao diện Swagger và các bộ lọc bảo mật:
Swashbuckle.AspNetCore.SwaggerUISwashbuckle.AspNetCore.Filters
Gói Filters giúp tích hợp nút nhập token JWT trực tiếp trên giao diện Swagger UI.
Mở rộng Dependency Injection
Tạo một lớp tiện ích để cấu hình SwaggerGen, bao gồm việc định nghĩa bảo mật Bearer JWT và nạp các file XML注释. Lớp này giúp giảm thiểu code lặp lại trong Program.cs hoặc Startup.cs.
public static class SwaggerServiceExtensions
{
public static void RegisterSwaggerDocumentation(this IServiceCollection services, string applicationBasePath)
{
services.AddSwaggerGen(options =>
{
// Cấu hình bảo mật JWT
options.AddSecurityDefinition("Bearer", new OpenApiSecurityScheme
{
Description = "Nhập token JWT theo định dạng: Bearer {token}",
Name = "Authorization",
In = ParameterLocation.Header,
Type = SecuritySchemeType.ApiKey,
Scheme = "Bearer",
BearerFormat = "JWT"
});
options.AddSecurityRequirement(new OpenApiSecurityRequirement
{
{
new OpenApiSecurityScheme
{
Reference = new OpenApiReference
{
Type = ReferenceType.SecurityScheme,
Id = "Bearer"
}
},
Array.Empty<string>()
}
});
// Thông tin API
options.SwaggerDoc("v1", new OpenApiInfo
{
Version = "1.0.0",
Title = "API Documentation",
Description = "Tài liệu kỹ thuật cho hệ thống WebAPI",
Contact = new OpenApiContact
{
Name = "Development Team",
Email = "dev@example.com"
}
});
// Nạp file XML注释
var directory = new DirectoryInfo(applicationBasePath);
var xmlFiles = directory.GetFiles("*.xml");
foreach (var file in xmlFiles)
{
var xmlPath = Path.Combine(applicationBasePath, file.Name);
options.IncludeXmlComments(xmlPath, includeControllerXmlComments: true);
}
});
}
}
Mở rộng Middleware Pipeline
Để truy cập Swagger UI ngay tại đường dẫn gốc thay vì /swagger, cần tùy chỉnh middleware. Lưu ý khi đặt RoutePrefix rỗng, cấu hình launch settings cũng cần điều chỉnh tương ứng.
public static class SwaggerPipelineExtensions
{
public static IApplicationBuilder InitializeSwaggerUI(this IApplicationBuilder app, string version = "v1")
{
app.UseSwagger();
app.UseSwaggerUI(options =>
{
options.SwaggerEndpoint($"/swagger/{version}/swagger.json", version.ToUpper());
// Đặt rỗng để truy cập tại root
options.RoutePrefix = string.Empty;
});
return app;
}
}
Cấu hình Launch Settings
Khi RoutePrefix được đặt là chuỗi rỗng, cần sửa file launchSettings.json để trỏ launchUrl về chuỗi rỗng hoặc dấu cách, tránh việc trình duyệt tự động thêm hậu tố /swagger gây lỗi 404.
"launchUrl": " "
Xử lý xung đột HTTPS Redirection và Authentication
Trong quá trình phát triển, có thể gặp tình huống gọi API qua Swagger UI trả về lỗi 401 Unauthorized, trong khi gọi qua Postman vẫn thành công (200 OK). Nguyên nhân thường do middleware app.UseHttpsRedirection().
Khi middleware này hoạt động, nó sẽ强制 chuyển hướng các request HTTP sang HTTPS. Trong quá trình chuyển hướng này, header Authorization chứa token JWT có thể bị mất hoặc không được truyền đi đúng cách ở request đầu tiên. Swagger UI thường mặc định gọi HTTP local, dẫn đến việc bị redirect và mất token.
Để khắc phục trong môi trường development, có thể tạm thời comment dòng app.UseHttpsRedirection() hoặc đảm bảo Swagger UI được cấu hình gọi trực tiếp qua HTTPS ngay từ đầu.