Add Swagger to ASPNET Core 20 Web API

Add Swagger to ASP.NET Core 2.0 Web API

Testing WEB APIs is a challenge, and it has a dependency on various third-party tools for proper and efficient testing. But swagger can make it easy. Swagger is an UI representation of your RESTful API. Swagger UI allows anyone — be it your development team or your end consumers — to visualize and interact with the API’s resources having none of the implementation logic in place. It’s automatically generated from your Swagger specification, with the visual documentation, making it easy for back-end implementation and client-side consumption. Earlier, I posted about adding swagger with ASP.NET Core but it no longer works with ASP.NET Core 2.0 due to new changes with ASP.NET Core 2.0. In this post, we’ll see how to add Swagger to ASP.NET Core 2.0 Web API.

Add Swagger to ASP.NET Core 2.0 Web API

Create a ASP.NET Core 2.0 WEB API project and install Swashbuckle.AspNetCore nuget package. Swashbuckle comprises three packages – a Swagger generator, middleware to expose the generated Swagger as JSON endpoints and middleware to expose a swagger-ui that’s powered by those endpoints. They can be installed together, via the Swashbuckle.AspNetCore meta-package. Like:

PM > Install-Package Swashbuckle.AspNetCore

The default template has ValuesContoller with API action method for all HTTP verbs. We’ll use the same for this post for showing Swagger UI.

Open Startup.cs file to add swagger service to middleware. Like:
And enable the Swagger UI in Configure() method.
This is all required to set up Swagger. The one last thing to do is to change the application launch URL so that Swagger UI loads on launch. To set Swagger UI as launch URL, right-click on Project -> select properties -> navigate to debug tab. On debug tab, change Launch Browser value to “swagger”.

ASP.NET Core Set Swagger as Launch URL

Run the APP and you should see Swagger UI for ValuesContoller.

ASP.NET Core Set Swagger UI

Swagger uses different colors for each HTTP verb to differentiate API actions. Clicking on any method will give you details about accepted parameters, return type and allows you to test the method.

This is achieved with minimal configuration and without any customization. Swagger can be customized to include method’s XML comments, showing enum values as string values and generating different swagger document for different API version.

Show action’s XML Comments

We all are familiar with XML comments for documentation. By default, swagger does not show XML comments. There is an option to display them with Swagger UI. First, we need to ensure that when the project is built, all the XML comments get saved in an XML file. Swagger will use this file to show XML comments on the Swagger UI.

To save XML comments in a file, right-click on the project -> properties and navigate to the build tab. On this tab, check “XML documentation file” option.

ASP.NET Core Set Swagger UI XML Setting

By enabling this option, xml comments are saved in an XML file with the name [your assembly].xml. This file is located at bin\[Debug/Release]\netcoreapp2.0 folder. We need to pass this path Swashbuckle’s IncludeXMLComments method.

Add a method in Startup.cs to get the path of generated XML. This code to get the XML path will work in your local environment as well as in the production environment.

private string GetXmlCommentsPath()
{
    var app = PlatformServices.Default.Application;
    return System.IO.Path.Combine(app.ApplicationBasePath, "ASPNETCoreSwaggerDemo.xml");
}

Next, add code to include XML comments in ConfigureService method. Like:

services.AddSwaggerGen(c =>
{
   c.IncludeXmlComments(GetXmlCommentsPath());
}

Next, add XML comments to our actions. Here is XML comment for Delete method.

// DELETE api/values/5
/// <summary>
/// Delete API Value
/// </summary>
/// <remarks>This API will delete the values.</remarks>
/// <param name="id"></param>
[HttpDelete("{id}")]
public void Delete(int id)
{
}

Now run the app, you should see XML comments.
ASP.NET Core Set Swagger UI XML Comments

Showing Enum values as string

You can display the enum value as a string in the Swagger UI using DescribeAllEnumsAsStrings method. Like:

services.AddSwaggerGen(c =>
{
   c.IncludeXmlComments(GetXmlCommentsPath());
   c.DescribeAllEnumsAsStrings();
}

To see this in action, Let’s add an enum and modify Get method to accept enum type parameter.

public enum ValueType
{
    Number,
    Text
}

[HttpGet("{id}")]
public string Get(int id, ValueType type)
{
    return "value";
}

You should see the string value of enum are populated in the dropdown, instead of number (which is default).

Swagger With DescribeAllEnumsAsStrings

There is also a method named DescribeStringEnumsInCamelCase to convert enum string values in camel case.

Different swagger documents for different API versions

If you have multiple versions of your WEB API, then you can use swagger to generate the different document based on the selected version. Like:
Read this post to find out how to create/support multiple versions of the ASP.NET Core Web API. We also need to update the swagger UI to show multiple endpoints. They’ll be listed in the top right corner of the page, allowing users to toggle between the different documents.

Different swagger documents for different API versions

You can find the source code in the Github.

Conclusion

Swagger is a great tool to test your RESTFul APIs. Once integrated, it creates a simple UI to list down all your APIs actions and provide details about the request and response object for each API action. Integration with ASP.NET Core 2.0 is also straightforward and requires minimal efforts. Swagger also offers various customization to suit your needs.

Thank you for reading. Keep visiting this blog and share this in your network. Please put your thoughts and feedback in the comments section.

4 thoughts on “Add Swagger to ASP.NET Core 2.0 Web API

    1. Dmitry,

      Swagger out of the box doesn’t have this kind of UI but it can be easily tweaked and customized. To tweak the look and feel, you can inject additional CSS stylesheets by adding them to your wwwroot folder and specifying the relative paths in the middleware options:

      app.UseSwaggerUI(c =>
      {

      c.InjectStylesheet(“/swagger-ui/custom.css”);
      }

Leave a Reply

Your email address will not be published. Required fields are marked *

8 − 6 =