How to Add Swagger in .NET 9? – Reliable Hosting ASP.NET Reviews
ASP.NET Hosting

How to Add Swagger in .NET 9?

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.

swagger

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.

api

ASP.NET Core 8.0.11 Hosting Recommendation

HostForLIFE.eu
HostForLIFE.eu is a popular recommendation that offers various hosting choices. Starting from shared hosting to dedicated servers, you will find options fit for beginners and popular websites. It offers various hosting choices if you want to scale up. Also, you get flexible billing plans where you can choose to purchase a subscription even for one or six months.