To add Swagger to a .NET Core 8 Web API project, follow these steps:
You need to install the Swashbuckle.AspNetCore package, which provides the necessary tools for integrating Swagger into your project.
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
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();
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:
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.
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.
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
}
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",
});
});