Swagger in ASP.
NET Core Web API
Swagger is a powerful tool for documenting and consuming RESTful web services. Using Swagger in
ASP.NET Core Web API typically involves integrating the Swashbuckle library, which is a .NET
implementation of Swagger. Remember to properly secure and restrict access to Swagger endpoints
and documentation in a production environment.
Method 2: Installing Swagger API using NuGet Package Manager
Let us see how to add the Swagger Packages to our Project. To Add Swagger, open the NuGet
Package Manager window and then search for Swashbuckle.AspNetCore is in the browse tab, as
shown in the image below. Then, choose the Swashbuckle.AspNetCore package, select the project
where you want to install this package, and finally, click on the Install button, as shown in the image
below.
Configure Swagger Services:
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen();
Enable Swagger Middleware Components:
Once we configure the Swagger API services to built-in dependency injection container, then we need
to register the Swagger Middleware components to the Application Request Processing Pipeline. To
enable Swagger Middleware, add the following within the Main method of the Program class.
if (app.Environment.IsDevelopment())
{
app.UseSwagger();
app.UseSwaggerUI();
}
Customizing Swagger in .NET 8
Customizing Swagger allows you to customize the Swagger UI and the generated OpenAPI
specification to better suit your project's needs. This can include setting up custom information, such
as API descriptions and contact information, as well as configuring Swagger to understand more
complex or custom aspects of your API.
You can customize the Swagger metadata by configuring the SwaggerGen options in Program.cs. So,
modify AddSwaggerGen service as follows. As you can see here, we have provided more information
about our APIs, like, Title, Version, Description, TermsOfService, Contact, License.
builder.Services.AddSwaggerGen(c =>
{
c.SwaggerDoc("V10", new OpenApiInfo
{
Title = "My Custom API",
Version = "V10",
Description = "A Brief Description of My APIs",
TermsOfService = new Uri("https://dotnettutorials.net/privacy-policy/"),
Contact = new OpenApiContact
{
Name = "Support",
Email = "support@dotnettutorials.net",
Url = new Uri("https://dotnettutorials.net/contact/")
},
License = new OpenApiLicense
{
Name = "Use Under XYZ",
Url = new Uri("https://dotnettutorials.net/about-us/")
}
});
});
By default, Swagger API looks for the Version V1, but here, we have changed the version to V10. So,
we also need to configure the same into the Request Processing Pipeline. So, next modify the
UseSwaggerUI as follows:
app.UseSwaggerUI(c =>
{
c.SwaggerEndpoint("/swagger/V10/swagger.json", "My API V10");
});