How to Add Swagger in .NET 9?

Introduction

Swagger is an essential tool for documenting and testing APIs. In .NET 9, integrating Swagger with Minimal APIs or traditional controllers is straightforward. This article will guide you through the process step by step.

Prerequisites

  • .NET 9 SDK installed
  • A .NET 9 Web API project
  • Visual Studio or any preferred code editor

Create a New API Project

Swagger

Click right on the project, go to Manag Nuget Package.. as below image and install it.

MoviesAPI

Open Program.cs and update the code below.

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();

Open launchSettings.json  from the Properties folder and add the below code.

{
  "$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"
        }
    }
  }
}

Remember, please run the project with https. See the output below.

Project output


Similar Articles