It is no longer actively maintained and has been remove from .NET 9 templates. [1]
dotnet add package Swashbuckle.AspNetCore
Program.cs
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen();
if (app.Environment.IsDevelopment())
{
app.UseSwagger()
.UseSwaggerUI();
}
Installation Old
dotnet add package Swashbuckle.AspNetCore
Startup.cs
publicvoidConfigureServices(IServiceCollectionservices)
{
services.AddControllers();
services.AddSwaggerGen(c =>
{
c.SwaggerDoc("v1", newOpenApiInfo { Title = "EFWebApi", Version = "v1" });
});
}
publicvoidConfigure(IApplicationBuilderapp, IWebHostEnvironmentenv)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
app.UseSwagger();
app.UseSwaggerUI(c =>
{
c.SwaggerEndpoint("/swagger/v1/swagger.json", "EFWebApi v1");
c.RoutePrefix = string.Empty; // serve the Swagger UI at the app's root (http://localhost:<port>/)
});
}
Usage
Controllers/ItemController.cs
[ApiController]
[Route("[controller]")]
[Produces("application/json")] // set the Media typepublicclassItemController : ControllerBase
{
[HttpGet]
[ProducesResponseType(typeof(IEnumerable<Item>), StatusCodes.Status200OK)] // set the status code and the return typepublicIActionResultGet() { /* ... */ }
}
builder.Services.AddSwaggerGen(
options =>
{
c.SwaggerDoc("v1", newOpenApiInfo { Title = "My Web Api", Version = "v1" });
// Set the comments path for the Swagger JSON and UI.varxmlFilename = $"{Assembly.GetExecutingAssembly().GetName().Name}.xml";
options.IncludeXmlComments(Path.Combine(AppContext.BaseDirectory, xmlFilename));
});
}
Controllers/ItemController.cs
[Produces("application/json")]
publicclassMyController() : ControllerBase
{
///<summary>Get all the items.</summary>///<remarks>/// Sample request:////// GET /item///</remarks>///<response code="200">Returns all the items.</response>
[HttpGet]
publicIEnumerable<Item> GetAll() { /* ... */ }
///<summary>Update an item.</summary>///<param name="timeSeries">The new time series to add.</param>///<remarks>/// Sample request:////// PUT /item/9///</remarks>
[HttpPut("{id}")]
[ProducesResponseType(StatusCodes.Status204NoContent)] // by default returning void or Task is associated to status code 200publicTaskUpdateAsync(intid, CreateUpdateItemQueryquery) { /* ... */ }