Swagger/OpenAPI Generation for C# (.NET): Swashbuckle and NSwag
Documenting REST APIs is an integral part of modern C# (.NET) development. The OpenAPI specification (formerly known as Swagger) allows you to describe endpoints, data models, parameters, and responses in a unified, machine-readable format (JSON/YAML). In the .NET Core / .NET 5+ ecosystem, there are two main tools for automatic OpenAPI specification generation: Swashbuckle.AspNetCore and NSwag. Both tools integrate into ASP.NET Core, analyze your code, and create interactive documentation (Swagger UI).
Swashbuckle.AspNetCore: The Classic Choice
Swashbuckle is the most popular package for generating Swagger/OpenAPI in .NET. It automatically builds the specification based on controllers, routing attributes, and model annotations. Supports OpenAPI 3.0 and Swagger 2.0.
Installation and Basic Setup
dotnet add package Swashbuckle.AspNetCoreIn the Program.cs file (or Startup.cs for older versions), add services and middleware:
var builder = WebApplication.CreateBuilder(args);
builder.Services.AddControllers();builder.Services.AddEndpointsApiExplorer();builder.Services.AddSwaggerGen(c =>{ c.SwaggerDoc("v1", new OpenApiInfo { Title = "My API", Version = "v1", Description = "Example API for an educational website" });});
var app = builder.Build();
if (app.Environment.IsDevelopment()){ app.UseSwagger(); app.UseSwaggerUI(c => { c.SwaggerEndpoint("/swagger/v1/swagger.json", "My API v1"); });}
app.MapControllers();app.Run();After launching, navigate to /swagger — an interactive UI will open where you can test endpoints directly from the browser.
Adding XML Comments
To include descriptions from XML comments in the documentation, enable XML generation in the .csproj file:
<PropertyGroup> <GenerateDocumentationFile>true</GenerateDocumentationFile></PropertyGroup>Then specify the path to the XML file in AddSwaggerGen:
builder.Services.AddSwaggerGen(c =>{ var xmlFile = $"{Assembly.GetExecutingAssembly().GetName().Name}.xml"; var xmlPath = Path.Combine(AppContext.BaseDirectory, xmlFile); c.IncludeXmlComments(xmlPath);});Now comments from the code will be displayed in the Swagger UI.
Example Controller with Annotations
[ApiController][Route("api/[controller]")]public class ProductsController : ControllerBase{ /// <summary> /// Get a list of all products /// </summary> [HttpGet] public ActionResult<IEnumerable<Product>> GetAll() { return Ok(new List<Product>()); }
/// <summary> /// Get a product by ID /// </summary> /// <param name="id">Product identifier</param> [HttpGet("{id}")] public ActionResult<Product> GetById(int id) { return Ok(new Product { Id = id, Name = "Example" }); }}NSwag: A Versatile Tool with Client Generation
NSwag is a more powerful alternative. In addition to generating documentation, it can create C# clients for APIs, TypeScript clients, and generate code based on external OpenAPI specifications.
Installation and Setup
dotnet add package NSwag.AspNetCoreSetup in Program.cs:
builder.Services.AddOpenApiDocument(config =>{ config.Title = "My API (NSwag)"; config.Version = "v1"; config.Description = "API generated using NSwag";});
// ...