Easy Way to Setup Swagger in ASP.NET Core - Windows ASP.NET Core Hosting 2024 | Review and ComparisonWindows ASP.NET Core Hosting 2024 | Review and Comparison

Setting up Swagger in an ASP.NET Core application is an essential part of API documentation, making it easy for developers to visualize and test API endpoints. Swagger generates interactive documentation and allows for testing directly in the browser. This guide will cover how to set up Swagger in ASP.NET Core step-by-step and customize it according to your requirements.

Setting Up the ASP.NET Core Project

To begin, ensure you have the following prerequisites:

  • Visual Studio (or Visual Studio Code)
  • .NET SDK

Create a new ASP.NET Core Web API project using Visual Studio or through the command line:

dotnet new webapi -n SwaggerExample
cd SwaggerExample

Open the project in Visual Studio or your preferred code editor.

Installing the Swagger NuGet Package

ASP.NET Core provides a package for Swagger known as Swashbuckle.AspNetCore. You can install it via the Package Manager Console or by using the following CLI command:

dotnet add package Swashbuckle.AspNetCore

After the installation, you’ll be able to configure Swagger to automatically generate documentation for your API.

Configuring Swagger in ASP.NET Core

Open Program.cs or Startup.cs (depending on the project version). You’ll need to add Swagger services in the ConfigureServices method and configure the Swagger middleware in the Configure method.

Step 1: Add Swagger Services

In Program.cs (or Startup.cs for older versions), locate the ConfigureServices method and add Swagger services.

using Microsoft.OpenApi.Models;

var builder = WebApplication.CreateBuilder(args);

// Register Swagger services
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen(options =>
{
    options.SwaggerDoc("v1", new OpenApiInfo
    {
        Version = "v1",
        Title = "My API",
        Description = "An ASP.NET Core Web API for demonstrating Swagger"
    });
});

var app = builder.Build();

The SwaggerDoc method configures the basic information for your API, like version, title, and description.

Step 2: Configure Swagger Middleware

Still in Program.cs (or Startup.cs), add the following code to configure Swagger middleware. Add this just before app.Run():

if (app.Environment.IsDevelopment())
{
    app.UseSwagger();
    app.UseSwaggerUI(options =>
    {
        options.SwaggerEndpoint("/swagger/v1/swagger.json", "My API V1");
        options.RoutePrefix = string.Empty; // Set Swagger UI at the app's root
    });
}

The UseSwagger method adds Swagger middleware, while UseSwaggerUI provides the interactive UI to visualize the API. Setting RoutePrefix to an empty string makes Swagger available at the app’s root URL.

Customizing Swagger Documentation

With Swagger set up, you can now enhance it with custom options to suit your needs, such as adding XML comments, setting up security schemes, and organizing API groups.

Adding XML Comments

XML comments allow Swagger to read descriptions of API endpoints, parameters, and responses from comments within your code. To enable XML comments:

  1. Right-click on the project, go to Properties > Build and check XML documentation file.

2. In the Swagger configuration, enable XML comments by adding the following code:

var xmlFilename = $"{Assembly.GetExecutingAssembly().GetName().Name}.xml";
options.IncludeXmlComments(Path.Combine(AppContext.BaseDirectory, xmlFilename));

3. Document your controllers and methods using XML comments:

/// <summary>
/// Retrieves all products.
/// </summary>
[HttpGet]
public IEnumerable<Product> GetAllProducts()
{
// Method implementation
}

Organizing with Tags

Using tags allows you to group endpoints in Swagger. You can specify tags on controller actions:

[HttpGet]
[SwaggerOperation(Tags = new[] { "Products" })]
public IEnumerable<Product> GetAllProducts()
{
    // Method implementation
}

This approach helps in organizing complex APIs with multiple endpoints.

Securing the Swagger Documentation

For APIs that require authorization, you can add security schemes to Swagger UI. For example, to add a Bearer token for JWT authentication:

  1. Update AddSwaggerGen in Program.cs:
options.AddSecurityDefinition("Bearer", new OpenApiSecurityScheme
{
    In = ParameterLocation.Header,
    Description = "Please insert JWT with Bearer into field",
    Name = "Authorization",
    Type = SecuritySchemeType.ApiKey
});

options.AddSecurityRequirement(new OpenApiSecurityRequirement
{
    {
        new OpenApiSecurityScheme
        {
            Reference = new OpenApiReference
            {
                Type = ReferenceType.SecurityScheme,
                Id = "Bearer" 
            }
        },
        new string[] { }
    }
});

This configuration adds an “Authorize” button on Swagger UI, where users can input a JWT token for authentication.

Testing the API with Swagger UI

  • Run the application (press F5 or use dotnet run).
  • Open your browser and go to https://localhost:{port} (depending on your configuration).
  • Swagger UI should be visible, showing your API endpoints and allowing you to test each one by sending requests and viewing responses.

Using Swagger Annotations for Better Documentation

The Swashbuckle.AspNetCore.Annotations package allows you to use annotations to further enhance Swagger documentation.

dotnet add package Swashbuckle.AspNetCore.Annotations

You can then use attributes like [SwaggerOperation] and [SwaggerResponse] to add details to specific actions.

Example:

[HttpGet("{id}")]
[SwaggerOperation(Summary = "Get product by ID", Description = "Fetches a product by its ID")]
[SwaggerResponse(200, "Returns the product for the given ID")]
[SwaggerResponse(404, "Product not found")]
public ActionResult<Product> GetProductById(int id)
{
// Method implementation
}

Creating Different Versions of Swagger Documentation

For APIs with multiple versions, you can configure Swagger to create separate documentation versions.

  1. Update SwaggerGen to support multiple versions:
options.SwaggerDoc("v1", new OpenApiInfo { Title = "My API", Version = "v1" });
options.SwaggerDoc("v2", new OpenApiInfo { Title = "My API", Version = "v2" });

2. Specify different [ApiVersion] attributes in controllers and configure the SwaggerEndpoint accordingly.

Swagger Custom UI Styling

You can customize the look and feel of Swagger UI by providing custom CSS or JavaScript files.

options.InjectStylesheet("/css/custom-swagger.css");
options.InjectJavascript("/js/custom-swagger.js");

Add custom styles or JavaScript to the /wwwroot/css and /wwwroot/js folders in your project.

Conclusion

Integrating Swagger in ASP.NET Core is a valuable addition for any API project. With Swagger, you gain a powerful tool for automatic API documentation, allowing developers to interactively explore and test API endpoints. By customizing with XML comments, security options, and multiple versions, Swagger can provide well-organized and secure documentation that is easy to maintain.

Setting up Swagger in ASP.NET Core simplifies the documentation process, provides an interactive way to test APIs, and enhances overall API maintainability, ensuring your team has easy access to detailed information on each endpoint.