visit
So after you create your API project, you need to install
Swashbuckle.AspNetCore
. I'm using . Then you need to register it in the Startup.cs. I'm doing a basic setup here for brevity sake, but feel free to explore the configuration options available.public void ConfigureServices(IServiceCollection services)
{
services.AddSwaggerGen(options =>
{
options.SwaggerDoc("v1", new OpenApiInfo()
{
Description="Well documented api",
Title = "Sandbox Api"
});
});
//other stuff
}
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
app.UseSwagger();
app.UseSwaggerUI(c =>
{
c.SwaggerEndpoint("/swagger/v1/swagger.json", "Sandbox Api");
});
//other stuff...
}
As you can see, I have two projects in my solution because I decided to put my models in a separate library project. I will also need to document these classes and if this is your use case too, then you mustn't forget to enable xml documentations for those projects too. Next, instruct swashbuckle to use those files. I'm adding the following two lines to my ConfigureServices method in the AddSwaggerGen options:
options.IncludeXmlComments(Path.GetDirectoryName(Assembly.GetExecutingAssembly().CodeBase) + "\\SandboxApi.xml", true);
options.IncludeXmlComments(Path.GetDirectoryName(Assembly.GetExecutingAssembly().CodeBase) + "\\Models.xml");
/// <summary>
/// A controller for CRUD operations with weather forecast
/// </summary>
[ApiController]
[Route("[controller]")]
public class WeatherForecastController : ControllerBase
{
private static readonly string[] Summaries = new[]
{
"Freezing", "Bracing", "Chilly", "Cool", "Mild", "Warm", "Balmy", "Hot", "Sweltering", "Scorching"
};
...
/// <summary>
/// Detailed weather forecast
/// </summary>
public class WeatherForecast
{
/// <summary>
/// The date for the forecast
/// </summary>
public DateTime Date { get; set; }
Usage of
<remarks>
, <returns>
and <example>
is also supported. You can see the explanations showing up for the endpoints and you can explore the schemas at the bottom of the swagger index page.public class WeatherPostOperationFilter : IOperationFilter
{
public void Apply(OpenApiOperation operation, OperationFilterContext context)
{
if (operation.OperationId != "Weather_Post")
return;
operation.RequestBody = new OpenApiRequestBody()
{
Content = new Dictionary<string, OpenApiMediaType> {
{"multipart/form-data",
new OpenApiMediaType()
{
Schema = context.SchemaGenerator
.GenerateSchema(typeof(WeatherForecast), context.SchemaRepository)
}
}
}
};
}
}
[HttpPost(Name ="Weather_Post")]
public IEnumerable<WeatherForecast> Post()
{
//...
Then register the filter in the services.AddSwaggerGen call in the ConfigureServices method:
options.OperationFilter<WeatherPostOperationFilter>();