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
Next, navigate to the package manager console.
Once there, use the Browse tab to search for Swashbuckle.AspNetCore, then click install to add it to your project
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();
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();
}
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;
Now, when you run your application, the server and port name should be generated in a prompt like so;
To see the Swagger UI, on your browse, Simply add /swagger/index.html to your server and port number.
Happy Coding!!
Top comments (0)