DEV Community

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

Posted on

3 1

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!!

Hostinger image

Get n8n VPS hosting 3x cheaper than a cloud solution

Get fast, easy, secure n8n VPS hosting from $4.99/mo at Hostinger. Automate any workflow using a pre-installed n8n application and no-code customization.

Start now

Top comments (0)

A Workflow Copilot. Tailored to You.

Pieces.app image

Our desktop app, with its intelligent copilot, streamlines coding by generating snippets, extracting code from screenshots, and accelerating problem-solving.

Read the docs

👋 Kindness is contagious

DEV shines when you're signed in, unlocking a customized experience with features like dark mode!

Okay