How to Add Swagger in .NET
By FoxLearn 2/28/2025 4:33:04 AM 13
Step 1: Create a New API Project
Start by creating a new .NET 9 Web API project if you don’t already have one. You can do this via the command line or your IDE.
Step 2: Install Swagger
Right-click on your project in Solution Explorer.
Select Manage NuGet Packages.
Search for
Swashbuckle.AspNetCore
and install it.
Step 3: Configure Swagger in Program.cs
Update your Program.cs
file to include Swagger services and middleware:
var builder = WebApplication.CreateBuilder(args); // Add services to the container. builder.Services.AddControllers(); builder.Services.AddEndpointsApiExplorer(); builder.Services.AddSwaggerGen(); var app = builder.Build(); // Configure the HTTP request pipeline. if (app.Environment.IsDevelopment()) { app.UseSwagger(); app.UseSwaggerUI(); } app.UseHttpsRedirection(); app.UseAuthorization(); app.MapControllers(); app.Run();
Step 4: Update launchSettings.json
Open the launchSettings.json
file located in the Properties
folder and add the following configuration to ensure Swagger launches automatically:
{ "$schema": "https://json.schemastore.org/launchsettings.json", "profiles": { "http": { "commandName": "Project", "dotnetRunMessages": true, "launchBrowser": false, "applicationUrl": "http://localhost:5250", "environmentVariables": { "ASPNETCORE_ENVIRONMENT": "Development" } }, "https": { "commandName": "Project", "dotnetRunMessages": true, "launchBrowser": true, "launchUrl": "swagger", "applicationUrl": "https://localhost:7026;http://localhost:5250", "environmentVariables": { "ASPNETCORE_ENVIRONMENT": "Development" } } } }
Step 5: Run the Project
Ensure you run the project using the
https
profile.Open your browser and navigate to the Swagger UI, typically available at
https://localhost:<port>/swagger
.
By following these steps, you can easily integrate Swagger into your .NET 9 Web API project, enhancing your API documentation and testing capabilities.
- Dynamic Menus in ASP.NET Core
- What is HSTS
- HTML5 Validation for ASP.NET Core
- Using HTML Range Inputs with ASP.NET Core TagHelpers
- Using HTML DataList with ASP.NET Core
- How to Use Conditional Middleware in ASP.NET Core
- How to use the FromServices attribute in ASP.NET Core
- How to use the Developer Exception Page in ASP.NET Core