How to Add Swagger in .NET
By FoxLearn 2/28/2025 4:33:04 AM 166
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.
- The name 'Session' does not exist in the current context
- Implementing Two-Factor Authentication with Google Authenticator in ASP.NET Core
- How to securely reverse-proxy ASP.NET Core
- How to Retrieve Client IP in ASP.NET Core Behind a Reverse Proxy
- Only one parameter per action may be bound from body in ASP.NET Core
- The request matched multiple endpoints in ASP.NET Core
- How to Create a custom model validation attribute in ASP.NET Core
- How to disable ModelStateInvalidFilter in ASP.NET Core