Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles
(untagged)

Documenting ASP.NET Core 2.0 Web API

0.00/5 (No votes)
4 Sep 2017 1  
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:

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

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

/// <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 has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here