How to add the swagger to ASP.NET Core?

Imagine you have the ASP.NET Core web application. Later, you decide to add some REST API functionality to the application. This is typically a natural part of the ASP.NET WebApi project. However, your project is ASP.NET project and NOT a WebApi project.

No problem, this works. To create a WebApi based REST API and to integrate the swagger, you must add the controller class to the project, as usual. But one more thing still is missing = Swagger!

To add the swagger, you need to do the following:

1 – Add the swagger nuget package

Open the project file and add the following reference (use the latest version):

Sure, you can also use the VS UI to add the package.

2 – Add required services

You need to add the Endpoint Explorer and the Swagger Generator:

builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen();

Activate the swagger generator and the swagger

Finally, you need to activate the swagger.

app.UseSwagger();
app.UseSwaggerUI();
~~~csharp