Click here to Skip to main content
15,884,007 members
Articles / Web Development / ASP.NET / ASP.NET Core

Documenting ASP.NET Core 2.0 Web API

Rate me:
Please Sign up or sign in to vote.
0.00/5 (No votes)
4 Sep 2017CPOL 8K   5  
How to add documentation and help pages for ASP.NET Core Web API. Continue reading...

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:

C#
public void ConfigureServices(
            IServiceCollection services)
        {
            services.AddSwaggerGen(options =>
            {
                options.SwaggerDoc("help", new Info
                {
                    Title = "Fiver.Api Help",
                    Version = "v1"
                });
            });

            // other services
        }

        public void Configure(
            IApplicationBuilder app,
            IHostingEnvironment env)
        {
            app.UseSwagger();
            app.UseSwaggerUI(options =>
            {
                options.SwaggerEndpoint(
                  "/swagger/help/swagger.json", "Fiver.Api Help Endpoint");
            });

            // other middleware
        }

The help page can be accessed via: [host]/swagger

Image 1

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:

C#
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.:

C#
/// <summary>
/// Adds a new movie
/// </summary>
/// <remarks>
/// A sample request body
/// 
///     POST /movies
///     {       
///         "title": "Thunderball",
///         "releaseYear": 1965,
///         "summary": "James Bond heads to The Bahamas to recover two nuclear 
///                        warheads stolen by SPECTRE"
///     }
/// </remarks>
/// <returns>Newly added movie</returns>
/// <response code="201">if movie created</response>
/// <response code="400">if input null or invalid</response>
[HttpPost]
[ProducesResponseType(typeof(MovieOutputModel), 201)]
[Produces("application/json", Type = typeof(MovieOutputModel))]

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



Comments and Discussions

 
-- There are no messages in this forum --