DEV Community

Cover image for How to use Swagger UI on a .NET 9 Web API project
Olabamiji Oyetubo
Olabamiji Oyetubo

Posted on

How to use Swagger UI on a .NET 9 Web API project

If you didn’t know, with the release of .NET 9, Swagger UI for Web API projects no longer comes out of the box. This tutorial will show you how to add Swagger configuration to .NET 9 projects.

First, create a new ASP .NET Core Web API project and set your target framework to .NET 9

Create Project

Next, navigate to the package manager console.

Go to Package manager Console
Once there, use the Browse tab to search for Swashbuckle.AspNetCore, then click install to add it to your project

Install Swashbuckle

After the package has been successfully installed, navigate to your Program.cs class and just above the builder.Build() method, add this line of code;

builder.Services.AddSwaggerGen();
Enter fullscreen mode Exit fullscreen mode

This method registers the Swagger generator into the DI container, allowing your application to generate an OpenAPI specification for our API.
Next, modify the app.Environment.IsDevelopment() condition, so it looks like this;

if (app.Environment.IsDevelopment())
{
    app.UseSwagger();
    app.UseSwaggerUI();
}
Enter fullscreen mode Exit fullscreen mode

app.UseSwagger() serves the API documentation as OpenAPI JSON, while app.UseSwaggerUI() provides an interactive UI for testing endpoints.
Your Program.cs should look like this now;

Updated Program.cs
Now, when you run your application, the server and port name should be generated in a prompt like so;

Server and port
To see the Swagger UI, on your browse, Simply add /swagger/index.html to your server and port number.

Swagger UI page

Happy Coding!!

Top comments (0)