Problem
This post will show you how to add documentation and help pages for ASP.NET Core Web API.
Solution
Add NuGet package: Swashbuckle.AspNetCore
Update Startup
to add services and middleware for Swagger:
public void ConfigureServices(
IServiceCollection services)
{
services.AddSwaggerGen(options =>
{
options.SwaggerDoc("help", new Info
{
Title = "Fiver.Api Help",
Version = "v1"
});
});
}
public void Configure(
IApplicationBuilder app,
IHostingEnvironment env)
{
app.UseSwagger();
app.UseSwaggerUI(options =>
{
options.SwaggerEndpoint(
"/swagger/help/swagger.json", "Fiver.Api Help Endpoint");
});
}
The help page can be accessed via: [host]/swagger
Discussion
Swagger is a format to describe RESTful APIs and Swashbuckle generate these swagger documents.
Note: The name specified when configuring services via SwaggerDoc
method (e.g. “help” our sample code) must be the same as the specified in SwaggerEndpoint
method.
XML Documentation
Documents generated by Swagger can include XML documentation. This can be turned on from project Properties > Build tab and configuring swagger services:
var xmlDocPath = PlatformServices.Default.Application.ApplicationBasePath;
options.IncludeXmlComments(Path.Combine(xmlDocPath, "Fiver.Api.Help.xml"));
Using XML comments, data annotations on model and action attributes, we can produce detailed documentation that would be useful for the client developers, e.g.:
[HttpPost]
[ProducesResponseType(typeof(MovieOutputModel), 201)]
[Produces("application/json", Type = typeof(MovieOutputModel))]