Swagger in .NetCore


To add Swagger to a .NET Core 8 Web API project, follow these steps:

Step 1: Install the Swagger NuGet Package

You need to install the Swashbuckle.AspNetCore package, which provides the necessary tools for integrating Swagger into your project.

Add Swagger in .NetCore

You can also install NuGet Package Manager Console, In the NuGet Package Manager Console, run the following command

Install-Package Swashbuckle.AspNetCore -Version 6.5.0

Step 2: Configure Swagger in Program.cs

Modify the Program.cs file to configure Swagger in your application. You'll need to add the Swagger services and configure the Swagger middleware.

 

using GenerateToken;
using GenerateToken.BLL.Services;
using GenerateToken.Data;
using JswPoc.BLL.Middlewares;
using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.AspNetCore.Identity;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.IdentityModel.Tokens;
using System.IdentityModel.Tokens.Jwt;
using System.Text;


var builder = WebApplication.CreateBuilder(args);
// Add services to the container.

var connectionString = builder.Configuration.GetConnectionString("DefaultConnection");
builder.Services.AddDbContext<GenerateToken.Data.ApplicationDbContext>(options =>
options.UseSqlServer(connectionString));



builder.Services.AddIdentity<IdentityUser, IdentityRole>()
.AddEntityFrameworkStores<ApplicationDbContext>()
.AddDefaultTokenProviders();

builder.Services.AddAuthentication(options =>
{
options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
options.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
options.DefaultScheme = JwtBearerDefaults.AuthenticationScheme;
}).AddJwtBearer(o =>
{
o.TokenValidationParameters = new TokenValidationParameters
{
ValidIssuer = builder.Configuration["Jwt:Issuer"],
ValidAudience = builder.Configuration["Jwt:Audience"],
IssuerSigningKey = new SymmetricSecurityKey
(Encoding.UTF8.GetBytes(builder.Configuration["Jwt:Key"])),
ValidateIssuer = true,
ValidateAudience = true,
ValidateLifetime = false,
ValidateIssuerSigningKey = true
};
});

builder.Services.AddAuthorization();

builder.Services.AddScoped<IMaterialService, MaterialService>();
builder.Services.AddSwaggerGen();
// Add services to the container.
builder.Services.AddControllersWithViews();

var app = builder.Build();

// Configure the HTTP request pipeline.
if (!app.Environment.IsDevelopment())
{
app.UseExceptionHandler("/Home/Error");
// The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
app.UseHsts();
}

app.UseHttpsRedirection();
app.UseStaticFiles();

app.UseSwagger();
app.UseSwaggerUI(c =>
{
c.SwaggerEndpoint("/swagger/v1/swagger.json", "API V1");
});

app.UseRouting();

app.UseMiddleware<TokenMiddleware>();

app.UseAuthentication();
app.UseAuthorization();
app.MapControllerRoute(
    name: "default",
    pattern: "{controller=Home}/{action=Index}/{id?}");

app.Run();

Step 3: Test Swagger

  1. Run your application by pressing F5 or using dotnet run in the terminal.
  2. Once the application is running, navigate to https://localhost:{port}/swagger in your browser.
  3. You should see the Swagger UI, where you can interact with and test your API endpoints.
Add Swagger in .NetCore

Optional: Customize Swagger

You can further customize Swagger documentation by updating the AddSwaggerGen method to include details such as API title, version, and descriptions.

builder.Services.AddSwaggerGen(c =>
{
    c.SwaggerDoc("v1", new Microsoft.OpenApi.Models.OpenApiInfo
    {
        Title = "My API",
        Version = "v1",
        Description = "An API for demonstrating Swagger in .NET Core 8",
    });
});

This code is part of the configuration for integrating Swagger into a .NET Core API project. Here's a breakdown of each part:

builder.Services.AddSwaggerGen(c => { ... });

This line registers Swagger generation services in the application's dependency injection container. It allows Swagger to automatically generate API documentation for your controllers and endpoints.

  • builder.Services.AddSwaggerGen: This method adds and configures the Swagger generator. It defines how Swagger will generate and present your API documentation.
  • c => { ... }: This is a lambda expression that provides configuration options for Swagger inside the AddSwaggerGen method.

c.SwaggerDoc("v1", new Microsoft.OpenApi.Models.OpenApiInfo { ... });

This line defines a specific Swagger document for the API version. Swagger supports versioning, so this configuration sets up version 1 (v1) of your API.

  • c.SwaggerDoc("v1", ...): This method adds metadata for a specific version of the API. Here, "v1" is the identifier for the version. You can create different versions (e.g., "v2", "v3", etc.) for future iterations of your API.
  • new Microsoft.OpenApi.Models.OpenApiInfo { ... }: This is the object that contains metadata about the API. This information is displayed in the Swagger UI.

The OpenApiInfo Object

This object contains important details about the API

new Microsoft.OpenApi.Models.OpenApiInfo
{
    Title = "My API",            // The title of the API displayed in Swagger UI
    Version = "v1",              // The version of the API being described
    Description = "An API for demonstrating Swagger in .NET Core 8", // A description of what the API does
}
  1. Title - This sets the name of your API. It is displayed at the top of the Swagger UI. In this example, it’s set to "My API".
  2. Version - This defines the version of the API, here set to "v1". You can create multiple versions for your API, and each can have its own documentation.
  3. Description - A brief explanation of what your API does. This is visible in the Swagger UI and helps users understand the API's purpose.

Define Multiple API Versions in Program.cs

You need to modify the AddSwaggerGen method to register both versions (v1 and v2) in Swagger.

builder.Services.AddSwaggerGen(c =>
{
    // Define v1 of the API
    c.SwaggerDoc("v1", new Microsoft.OpenApi.Models.OpenApiInfo
    {
        Title = "My API",
        Version = "v1",
        Description = "Version 1 of My API",
    });

    // Define v2 of the API
    c.SwaggerDoc("v2", new Microsoft.OpenApi.Models.OpenApiInfo
    {
        Title = "My API",
        Version = "v2",
        Description = "Version 2 of My API with new features",
    });
});

Prev Next

Top Articles

  1. What is JSON
  2. How to convert a javaScript object in JSON object
  3. Some Important JSON Examples
  4. Common JSON Interview Question