How to Add Swagger in .NET

By FoxLearn 2/28/2025 4:33:04 AM   13
Swagger is a powerful tool for documenting and testing APIs. In .NET 9, integrating Swagger with Minimal APIs or traditional controllers is simple and efficient.

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

  1. Right-click on your project in Solution Explorer.

  2. Select Manage NuGet Packages.

  3. 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

  1. Ensure you run the project using the https profile.

  2. 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.