Adding Swagger to a C# WebApi

About Swagger

Swagger (https://swagger.io/) is a free open-source tool that enables easy documentation and testing of APIs. It is language agnostic.

Swashbuckle (https://github.com/domaindrivendev/Swashbuckle) is a .Net specific tool that adds Swagger to a .Net Web Api.

Installation

Install from Nuget

Install-Package Swashbuckle

Register Swagger

The Swashbuckle install should create a SwaggerConfig.cs file in the App_start Directory. This will allow you to configure Swagger in various ways.

Enable XML document generation

Open the project properties for your WebApi project, select the build tab and change the setting below:

Annotation 2019-02-20 111835

Update swagger config to use the XML comments

In the SwaggerConfig.cs file uncomment the line below:

c.IncludeXmlComments(GetXmlCommentsPath());

and add the method :

private static string GetXmlCommentsPath()
{
   var filepath = System.String.Format(@"{0}\bin\documentation.XML", System.AppDomain.CurrentDomain.BaseDirectory);
   return filepath;
}

Adding XML comments to code

On your controller and individual endpoints add the /// triple slash comments, for example

///
/// Search returns a paged, filterd list of events
///

///filters for the search ///number of entries to return per page ///page number to return ///name of column to sort by ///direction of sort /// A list of Events /// Success /// No Data Found /// Internal Server Error [Route(“Search”)] [HttpGet] [SwaggerResponse(200)] [ResponseType(typeof(IQueryable))] public IHttpActionResult GetList([FromUri] EventArguments parameters, [FromUri] int pageSize = 25, [FromUri] int pageNumber = 1, [FromUri] string sortColumn = “Id”, [FromUri] bool sortForward = true) { … }

 

Advertisements