Skip to content

Instantly share code, notes, and snippets.

@chrisfcarroll
Last active June 18, 2025 15:41
Show Gist options
  • Save chrisfcarroll/5278f76c6de0c71922e89f2a9ad28bd5 to your computer and use it in GitHub Desktop.
Save chrisfcarroll/5278f76c6de0c71922e89f2a9ad28bd5 to your computer and use it in GitHub Desktop.
.Net 9 webapi template with minimal api + Swagger + Swashbuckle

To recreate:

  1. dotnet new webapi
  2. Add packages Swashbuckle.AspNetCore and Swashbuckle.AspNetCore.Annotations to your csproj file.
  3. Change the Program.cs
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen(options =>
{
    options.SwaggerDoc("v1", new OpenApiInfo { Title = "WebApi9", Version = "v1" });
});
builder.Services.AddMvcCore().AddApiExplorer();

and

app.MapSwagger();
app.UseSwaggerUI(c =>
{
    c.SwaggerEndpoint("/swagger/v1/swagger.json", "WebApi9 v1");
    c.RoutePrefix = string.Empty; // Set Swagger UI at the app's root
});    
using Microsoft.OpenApi.Models;
var builder = WebApplication.CreateBuilder(args);
// Add services to the container.
// Learn more about configuring OpenAPI at https://aka.ms/aspnet/openapi
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen(options =>
{
options.SwaggerDoc("v1", new OpenApiInfo { Title = "Your SwaggerUI Title Here", Version = "v1", });
});
builder.Services.AddMvcCore().AddApiExplorer();
var app = builder.Build();
app.UseSwagger(c =>
{
c.PreSerializeFilters.Add((swaggerDoc, httpReq) =>
{
swaggerDoc.Servers = new List<OpenApiServer>
{
new OpenApiServer { Url = $"{httpReq.Scheme}://{httpReq.Host.Value}" }
};
});
});
app.UseSwaggerUI(c =>
{
c.RoutePrefix = string.Empty; // Set Swagger UI at the app's root
});
app.UseHttpsRedirection();
var summaries = new[]
{
"Freezing", "Bracing", "Chilly", "Cool", "Mild", "Warm", "Balmy", "Hot", "Sweltering", "Scorching"
};
app.MapGet("/weatherforecast", () =>
{
var forecast = Enumerable.Range(1, 5).Select(index =>
new WeatherForecast
(
DateOnly.FromDateTime(DateTime.Now.AddDays(index)),
Random.Shared.Next(-20, 55),
summaries[Random.Shared.Next(summaries.Length)]
))
.ToArray();
return forecast;
})
.WithName("GetWeatherForecast");
app.Run();
record WeatherForecast(DateOnly Date, int TemperatureC, string? Summary)
{
public int TemperatureF => 32 + (int)(TemperatureC / 0.5556);
}
<Project Sdk="Microsoft.NET.Sdk.Web">
<PropertyGroup>
<TargetFramework>net9.0</TargetFramework>
<Nullable>enable</Nullable>
<ImplicitUsings>enable</ImplicitUsings>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Microsoft.AspNetCore.OpenApi" Version="9.0.3" />
<PackageReference Include="Swashbuckle.AspNetCore" Version="9.0.1" />
<PackageReference Include="Swashbuckle.AspNetCore.Annotations" Version="9.0.1" />
</ItemGroup>
</Project>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment