Documenting APIs in ASP .NET Core
Thanks to Swagger and the ecosystem surrounding Swagger it's straight forward to develop great documentation for your ASP .NET Core Web APIs.
There is a .NET/C# project called Swashbuckle that will generate Swagger compatible documentation and output html documentation. The Swashbuckle project for ASP .NET Core is called Ahoy, continuing the pirate theme.
Install Swashbuckle for ASP .NET CORE via Nuget.
Install-Package Swashbuckle -Pre
Then add the following code to your Startup.cs
file:
public void ConfigureServices(IServiceCollection services)
{
services.AddMvc();
services.AddSwaggerGen(); // after AddMvc
}
public void Configure(IApplicationBuilder app)
{
app.UseMvc();
app.UseSwagger();
app.UseSwaggerUi(); // after UseMvc
}
Now you can access the raw Swagger json via the following url. In my case I'm running my site using port 51501 so please adjust the port number in the url according to your local environment.
Now you can access a nice HTML view of your API.
Customize Comments
The next step is to add a custom description via the triple slash xml comments.
Enable XML documentation file
via the project properties.
Update your Startup.cs
file to look like this:
public void ConfigureServices(IServiceCollection services)
{
services.AddMvc();
services.AddSwaggerGen();
services.ConfigureSwaggerGen(options => options.IncludeXmlComments(GetXmlCommentsPath()));
}
...
private string GetXmlCommentsPath()
{
var app = PlatformServices.Default.Application;
return Path.Combine(app.ApplicationBasePath, Path.ChangeExtension(app.ApplicationName, "xml"));
}
Here is an example of adding a custom description to the PingController
.
/// <summary>
/// Returns the current date and time in UTC.
/// </summary>
/// <returns></returns>
[HttpGet]
public DateTime Get()
{
return DateTime.UtcNow;
}
Customize Documentation UI
The Swashbuckle tools enable you to skin the documentation website with only a few steps.
- Create a
wwwroot/swagger/ui
folder in your project - Copy the index.html and skin.css to the
ui
folder from the example in Github - Add
app.UseStaticFiles();
to the beginning of theConfigure(IApplicactionBuilder app)
method in yourStartup.cs
file
Once you have completed the above steps you will see your documentation now looks something like the following:
Summary
This article showed you how to automatically generate Swagger documentation for your ASP .NET Core web apis. In addition, it was shown how to customize the comments in your api documentation and how to customize the look and feel of the documentation.