Install and Configure Swagger In A Web API Project (.NET 6.0).
"Swagger" is a tool that helps make it easier to put together API documentation, therefore making life easier for both creators and consumers of APIs.
Installing Swagger
Right-click on your project folder and select Manage Nuget Packages...
Make sure Browse is selected and search Swagger
- Select the package shown in the picture above
Swashbuckle.AspNetCore
and install. NOTE: Select version 6.X.X not a greater version 7.X.X upwards.
- Select the package shown in the picture above
Add and Configure Swagger Middleware.
- Add the Swagger generator to the services collection.
// Swagger - Add the Swagger generator to the services collection
builder.Services.AddSwaggerGen(option =>
{
option.SwaggerDoc("v1", new OpenApiInfo { Title = "ExpenseNerd API", Version = "v1" });
});
- Enable the middleware
// Swagger - Enable the middleware
app.UseSwagger();
app.UseSwaggerUI();
- The complete
Project.cs
file is below.
using Microsoft.OpenApi.Models;
var builder = WebApplication.CreateBuilder(args);
// Add services to the container.
builder.Services.AddControllers();
// Swagger - Add the Swagger generator to the services collection
builder.Services.AddSwaggerGen(option =>
{
option.SwaggerDoc("v1", new OpenApiInfo { Title = "ExpenseNerd API", Version = "v1" });
});
var app = builder.Build();
// Configure the HTTP request pipeline.
app.UseHttpsRedirection();
// Swagger - Enable the middleware
app.UseSwagger();
app.UseSwaggerUI();
app.UseAuthorization();
app.MapControllers();
app.Run();
NOTE: You may need to enable the middleware for the development environment if you proect is setup that way.
if (app.Environment.IsDevelopment())
{
app.UseWebAssemblyDebugging();
// Swagger - Enable the middleware
app.UseSwagger();
app.UseSwaggerUI();
}
else
{
app.UseExceptionHandler("/Error");
// The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
app.UseHsts();
}
You can go ahead and run your application adding /swagger
to the end of the url to test if swagger is installed. If it is you would see your API endpoints showing in your browser.