Swagger is a powerful tool for API documentation and testing. It provides a user-friendly interface to explore and interact with your API, which helps developers understand how to use it effectively. This guide covers how to set up and configure Swagger in an ASP.NET Core 8 Web API project, along with best practices and detailed explanations.
Swagger, now known as OpenAPI, is a framework for API documentation and testing. It allows you to describe the structure of your APIs so that machines can read them. The Swagger UI is an interactive web interface for exploring and testing your API endpoints.
Why Use Swagger?
First, you need to install the necessary NuGet packages.
dotnet add package Swashbuckle.AspNetCore
You need to configure Swagger in the Program.cs file to enable it in your ASP.NET Core project.
3.1 Add Swagger ServicesIn the Program.cs file, add the Swagger services in the ConfigureServices method.
var builder = WebApplication.CreateBuilder(args);
// Add services to the container
builder.Services.AddControllers();
// Add Swagger services
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen(options =>
{
options.SwaggerDoc('v1', new Microsoft.OpenApi.Models.OpenApiInfo
{
Version = 'v1',
Title = 'My API',
Description = 'An example API for demonstrating Swagger in ASP.NET Core 8'
});
// Optionally include XML comments (requires XML documentation file)
var xmlFilename = $'{System.Reflection.Assembly.GetExecutingAssembly().GetName().Name}.xml';
options.IncludeXmlComments(Path.Combine(AppContext.BaseDirectory, xmlFilename));
});
var app = builder.Build();
Configure the middleware to serve the Swagger UI in the Configure method.
if (app.Environment.IsDevelopment())
{
app.UseSwagger();
app.UseSwaggerUI(options =>
{
options.SwaggerEndpoint('/swagger/v1/swagger.json', 'My API V1');
options.RoutePrefix = string.Empty; // Serve the Swagger UI at the app's root
});
}
app.UseHttpsRedirection();
app.UseAuthorization();
app.MapControllers();
app.Run();
Swagger can automatically generate documentation from XML comments in your code. To enable this, you need to add XML comments to your controllers and models.
4.1 Enable XML Documentation FileIn the .csproj file, enable XML documentation file generation.
<PropertyGroup>
<GenerateDocumentationFile>true</GenerateDocumentationFile>
<NoWarn>$(NoWarn);1591</NoWarn>
</PropertyGroup>
Add XML comments to your controllers and models.
Example Controller:
/// <summary>
/// Products controller to manage product operations
/// </summary>
[ApiController]
[Route('api/[controller]')]
public class ProductsController : ControllerBase
{
/// <summary>
/// Gets all products
/// </summary>
/// <returns>List of products</returns>
[HttpGet]
public IActionResult GetProducts()
{
return Ok(new[] { 'Product1', 'Product2' });
}
/// <summary>
/// Gets a product by ID
/// </summary>
/// <param name='id'>Product ID</param>
/// <returns>The product with the specified ID</returns>
[HttpGet('{id}')]
public IActionResult GetProduct(int id)
{
return Ok($'Product{id}');
}
/// <summary>
/// Creates a new product
/// </summary>
/// <param name='product'>The product to create</param>
/// <returns>Confirmation of product creation</returns>
[HttpPost]
public IActionResult CreateProduct([FromBody] string product)
{
return CreatedAtAction(nameof(GetProduct), new { id = 1 }, product);
}
}
If your API uses authentication, you can configure Swagger to include the necessary security definitions and operations.
5.1 Configure Swagger for JWT AuthenticationAdd the following configuration to the AddSwaggerGen method in Program.cs.
builder.Services.AddSwaggerGen(options =>
{
options.SwaggerDoc('v1', new Microsoft.OpenApi.Models.OpenApiInfo
{
Version = 'v1',
Title = 'My API',
Description = 'An example API for demonstrating Swagger in ASP.NET Core 8'
});
options.AddSecurityDefinition('Bearer', new Microsoft.OpenApi.Models.OpenApiSecurityScheme
{
Description = 'JWT Authorization header using the Bearer scheme. Example: 'Authorization: Bearer {token}'',
Name = 'Authorization',
In = Microsoft.OpenApi.Models.ParameterLocation.Header,
Type = Microsoft.OpenApi.Models.SecuritySchemeType.ApiKey,
Scheme = 'Bearer'
});
options.AddSecurityRequirement(new Microsoft.OpenApi.Models.OpenApiSecurityRequirement
{
{
new Microsoft.OpenApi.Models.OpenApiSecurityScheme
{
Reference = new Microsoft.OpenApi.Models.OpenApiReference
{
Type = Microsoft.OpenApi.Models.ReferenceType.SecurityScheme,
Id = 'Bearer'
}
},
Array.Empty<string>()
}
});
// Optionally include XML comments (requires XML documentation file)
var xmlFilename = $'{System.Reflection.Assembly.GetExecutingAssembly().GetName().Name}.xml';
options.IncludeXmlComments(Path.Combine(AppContext.BaseDirectory, xmlFilename));
});
Explanation:
You can customize the Swagger UI to better fit your needs.
6.1 Customize Swagger UI in Program.cs
if (app.Environment.IsDevelopment())
{
app.UseSwagger();
app.UseSwaggerUI(options =>
{
options.SwaggerEndpoint('/swagger/v1/swagger.json', 'My API V1');
options.RoutePrefix = string.Empty; // Serve the Swagger UI at the app's root
options.DocumentTitle = 'My API Documentation';
options.InjectStylesheet('/swagger-ui/custom.css');
options.InjectJavascript('/swagger-ui/custom.js');
});
}
Explanation:
using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.IdentityModel.Tokens;
using System.Text;
var builder = WebApplication.CreateBuilder(args);
// Add services to the container
builder.Services.AddControllers();
// Add Swagger services
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen(options =>
{
options.SwaggerDoc('v1', new Microsoft.OpenApi.Models.OpenApiInfo
{
Version = 'v1',
Title = 'My API',
Description = 'An example API for demonstrating Swagger in ASP.NET Core 8'
});
options.AddSecurityDefinition('Bearer', new Microsoft.OpenApi.Models.OpenApiSecurityScheme
{
Description = 'JWT Authorization header using the Bearer scheme. Example: 'Authorization: Bearer {token}'',
Name = 'Authorization',
In = Microsoft.OpenApi.Models.ParameterLocation.Header,
Type = Microsoft.OpenApi.Models.SecuritySchemeType.ApiKey,
Scheme = 'Bearer'
});
options.AddSecurityRequirement(new Microsoft.OpenApi.Models.OpenApiSecurityRequirement
{
{
new Microsoft.OpenApi.Models.OpenApiSecurityScheme
{
Reference = new Microsoft.OpenApi.Models.OpenApiReference
{
Type = Microsoft.OpenApi.Models.ReferenceType.SecurityScheme,
Id = 'Bearer'
}
},
Array.Empty<string>()
}
});
var xmlFilename = $'{System.Reflection.Assembly.GetExecutingAssembly().GetName().Name}.xml';
options.IncludeXmlComments(Path.Combine(AppContext.BaseDirectory, xmlFilename));
});
var app = builder.Build();
if (app.Environment.IsDevelopment())
{
app.UseSwagger();
app.UseSwaggerUI(options =>
{
options.SwaggerEndpoint('/swagger/v1/swagger.json', 'My API V1');
options.RoutePrefix = string.Empty; // Serve the Swagger UI at the app's root
options.DocumentTitle = 'My API Documentation';
options.InjectStylesheet('/swagger-ui/custom.css');
options.InjectJavascript('/swagger-ui/custom.js');
});
}
app.UseHttpsRedirection();
app.UseAuthentication();
app.UseAuthorization();
app.MapControllers();
app.Run();
/// <summary>
/// Products controller to manage product operations
/// </summary>
[ApiController]
[Route('api/[controller]')]
public class ProductsController : ControllerBase
{
/// <summary>
/// Gets all products
/// </summary>
/// <returns>List of products</returns>
[HttpGet]
public IActionResult GetProducts()
{
return Ok(new[] { 'Product1', 'Product2' });
}
/// <summary>
/// Gets a product by ID
/// </summary>
/// <param name='id'>Product ID</param>
/// <returns>The product with the specified ID</returns>
[HttpGet('{id}')]
public IActionResult GetProduct(int id)
{
return Ok($'Product{id}');
}
/// <summary>
/// Creates a new product
/// </summary>
/// <param name='product'>The product to create</param>
/// <returns>Confirmation of product creation</returns>
[HttpPost]
public IActionResult CreateProduct([FromBody] string product)
{
return CreatedAtAction(nameof(GetProduct), new { id = 1 }, product);
}
}
Swagger is an invaluable tool for API documentation and testing. By integrating Swagger into your ASP.NET Core 8 Web API project, you can provide comprehensive and interactive documentation for your API. Following the best practices outlined in this guide will help you maintain clear and up-to-date API documentation, enhance discoverability, and improve the overall developer experience. This comprehensive guide equips you with the knowledge to effectively implement and customize Swagger in your ASP.NET Core 8 Web API projects.