What it is
Swashbuckle generates OpenAPI documents and a Swagger UI from ASP.NET Core controllers, models and XML documentation comments.
Register the generator and the UI middleware. Endpoint metadata, response type attributes and XML comments all feed the generated document.
Installation
dotnet add package Swashbuckle.AspNetCoreGetting started
The smallest useful thing you can do with it, and what each part means.
csharp
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen(o =>
{
o.SwaggerDoc("v1", new OpenApiInfo { Title = "Library API", Version = "v1" });
// Pull summaries and remarks from /// comments.
o.IncludeXmlComments(Path.Combine(AppContext.BaseDirectory,
$"{Assembly.GetExecutingAssembly().GetName().Name}.xml"));
});
if (app.Environment.IsDevelopment())
{
app.UseSwagger();
app.UseSwaggerUI(); // do not expose the UI publicly by default
}
/// <summary>Gets a book by id.</summary>
[HttpGet("{id}")]
[ProducesResponseType<BookDto>(StatusCodes.Status200OK)]
[ProducesResponseType(StatusCodes.Status404NotFound)]
public async Task<IActionResult> Get(int id) => ...;Advanced usage
Where the library earns its place over a simpler alternative.
csharp
o.AddSecurityDefinition("Bearer", new OpenApiSecurityScheme
{
Type = SecuritySchemeType.Http,
Scheme = "bearer",
BearerFormat = "JWT",
Description = "Paste the JWT, without the Bearer prefix.",
});
o.AddSecurityRequirement(new OpenApiSecurityRequirement
{
[new OpenApiSecurityScheme {
Reference = new OpenApiReference {
Type = ReferenceType.SecurityScheme, Id = "Bearer" } }] = Array.Empty<string>()
});
// The emitted swagger.json feeds client generation:
// npx openapi-typescript http://localhost:5000/swagger/v1/swagger.json -o api.d.tsErrors and fixes
The failures you are most likely to hit, and what actually resolves them.
- Failed to load API definition
- Generation threw — commonly two actions mapping to the same route and method. The exception detail is in the application log.
- XML comments do not appear
- GenerateDocumentationFile is not enabled in the csproj, or the path passed to IncludeXmlComments is wrong.
Best practices
- Annotate every endpoint with ProducesResponseType, including error statuses.
- Enable XML documentation generation in the csproj so summaries appear.
- Do not expose Swagger UI in production unless it is behind authentication.
- Consider the built-in Microsoft.AspNetCore.OpenApi for new projects on .NET 9 or later.
Background
Why it exists, and what it was reacting to.
For years Swashbuckle was included in the ASP.NET Core Web API template. .NET 9 replaced the default with the built-in Microsoft.AspNetCore.OpenApi, but Swashbuckle remains the richer option and still bundles the UI.
