// Learn more about configuring Swagger/OpenAPI at https://aka.ms/aspnetcore/swashbuckle
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
///<summary>Fetch all the items.</summary>///<param name="cancellationToken"></param>///<returns>All the items</returns>///<remarks>/// Sample request:////// GET /item///</remarks>///<response code="200">Returns all the items.</response>
[HttpGet]
[Produces("text/json")]
[ProducesResponseType(typeof(IEnumerable<Item>), StatusCodes.Status200OK)]
publicIActionResultGetAll() { /* ... */ }