How to use Swagger in ASP.NET Core

Take advantage of open source Swashbuckle to generate Swagger documents for your ASP.NET Core Web API.

How to use Swagger in ASP.Net Core
Thinkstock

You will often want to create documentation for your API. To create this documentation, you can take advantage of Swagger – a tool that can be used to provide a UI representation of your API with ease. Once you have generated Swagger documentation for your API, you can view the signature of your API methods and even test your API methods as well.

Swashbuckle is an open source project for generating Swagger documents. This article presents a discussion of how we can take advantage of Swashbuckle to generate interactive documentation for our RESTful API.

Create an ASP.NET Core project

First off, let’s create an ASP.NET Core project in Visual Studio. Assuming Visual Studio 2017 or Visual Studio 2019 is installed in your system, follow the steps outlined below to create a new ASP.NET Core project in Visual Studio.

  1. Launch the Visual Studio IDE.
  2. Click on “Create new project.”
  3. In the “Create new project” window, select “ASP.NET Core Web Application” from the list of templates displayed.
  4. Click Next. 
  5. In the “Configure your new project” window that is shown next, specify the name and location for the new project.
  6. Click Create. 
  7. In the “Create New ASP.NET Core Web Application” window, select .NET Core as the runtime and ASP.NET Core 2.2 (or later) from the drop-down list at the top.
  8. Select “API” as the project template to create a new ASP.NET Core Web API project. 
  9. Ensure that the check boxes “Enable Docker Support” and “Configure for HTTPS” are unchecked as we won’t be using those features here.
  10. Ensure that Authentication is set as “No Authentication” as we won’t be using authentication either.
  11. Click Create.

Following these steps will create a new ASP.NET Core project in Visual Studio. We’ll use this project in the subsequent sections of this article to examine how we can generate Swagger documentation for the ValuesController.

Install Swagger middleware in ASP.NET Core

If you have successfully created an ASP.NET Core project, the next thing you should do is add the necessary NuGet packages to your project. To do this, select the project in the Solution Explorer window, right-click and select “Manage NuGet Packages....” In the NuGet Package Manager window, search for the package Swashbuckle.AspNetCore and install it. Alternatively, you can install the package via the NuGet Package Manager Console as shown below.

PM> Install-Package Swashbuckle.AspNetCore

The Swashbuckle.AspNetCore package contains the necessary tools for generating API documents for ASP.NET Core.

Configure Swagger middleware in ASP.NET Core

To configure Swagger, write the following code in the ConfigureServices method. Note how the AddSwaggerGen extension method is used to specify the metadata for the API document.

services.AddSwaggerGen(c =>
            {
                c.SwaggerDoc("v1", new Info
                {
                    Version = "v1",
                    Title = "Swagger Demo",
                    Description = "Swagger Demo for ValuesController",
                    TermsOfService = "None",
                    Contact = new Contact() { Name = "Joydip Kanjilal",
                    Email = "joydipkanjilal@yahoo.com",
                    Url = "www.google.com" }
                });
            });

You should also enable Swagger UI in the Configure method as shown below.

app.UseSwagger();
app.UseSwaggerUI(c =>
{
   c.SwaggerEndpoint("/swagger/v1/swagger.json", "v1");
});

Here is the complete code of the Startup class for your reference.

using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Swashbuckle.AspNetCore.Swagger;
namespace IDGSwaggerDemo
{
    public class Startup
    {
        public Startup(IConfiguration configuration)
        {
            Configuration = configuration;
        }
        public IConfiguration Configuration { get; }
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddMvc().SetCompatibilityVersion
            (CompatibilityVersion.Version_2_2);   
            services.AddSwaggerGen(c =>
            {
                c.SwaggerDoc("v1", new Info
                {
                    Version = "v1",
                    Title = "Swagger Demo",
                    Description = "Swagger Demo for ValuesController",
                    TermsOfService = "None",
                    Contact = new Contact() { Name = "Joydip Kanjilal",
                    Email = "joydipkanjilal@yahoo.com",
                    Url = "www.google.com"
                }
                });
            });
        }
        public void Configure(IApplicationBuilder app,
       IHostingEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }
            app.UseMvc();
            app.UseSwagger();
            app.UseSwaggerUI(c =>
            {
                c.SwaggerEndpoint("/swagger/v1/swagger.json", "v1");
            });
        }
    }
}

This is all you need to do to get started with Swagger.

Browse the Swagger UI of your ASP.NET Core app

Now we’re ready to execute the application and browse the Swagger endpoint. The Swagger UI will appear as in Figure 1 below. Note how Swagger uses different colors for the HTTP verbs GET, PUT, POST, and DELETE. You can execute each of the endpoints shown in Figure 1 directly from the Swagger UI.

swagger aspnet core fig 1 IDG

Figure 1: Swagger in action. 

Create XML comments in your controller’s action methods

So far so good. In the Swagger document generated earlier, there were no XML comments. If you want to show XML comments in the Swagger document, then you simply write those comments in your controller’s action methods.

Let’s now write comments for each of the action methods in the ValuesController. Here is the updated version of the ValuesController with XML comments for each of the action methods.

  [Route("api/[controller]")]
    [ApiController]
    public class ValuesController : ControllerBase
    {
        /// <summary>
        /// Get action method without any argument
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        public ActionResult<IEnumerable<string>> Get()
        {
            return new string[] { "value1", "value2" };
        }
        /// <summary>
        /// Get action method that accepts an integer as an argument
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        [HttpGet("{id}")]
        public ActionResult<string> Get(int id)
        {
            return "value";
        }
        /// <summary>
        /// Post action method to add data
        /// </summary>
        /// <param name="value"></param>
        [HttpPost]
        public void Post([FromBody] string value)
        {
        }
        /// <summary>
        /// Put action method to modify data
        /// </summary>
        /// <param name="id"></param>
        /// <param name="value"></param>
        [HttpPut("{id}")]
        public void Put(int id, [FromBody] string value)
        {
        }
        /// <summary>
        /// Delete action method
        /// </summary>
        /// <param name="id"></param>
        [HttpDelete("{id}")]
        public void Delete(int id)
        {
        }
    }

Turn on XML comments in Swagger

Note that Swagger doesn’t show XML comments by default. You need to turn this feature on. To do this, right-click on Project, select Properties, and then navigate to the Build tab. In the Build tab, check the “XML documentation file” option to specify the location where the XML documentation file will be created.

You should also specify that the XML comments should be included when generating the Swagger document by writing the following code in the ConfigureServices method.

c.IncludeXmlComments(@"D:\Projects\IDG\IDGSwaggerDemo\IDGSwaggerDemo\IDGSwaggerDemo.xml");

And that’s all you need to do to turn XML comments on in Swagger.

Set the launch URL for the app to Swagger UI

You can change your application launch URL to specify that the Swagger UI will be loaded when the application is launched. To do this, right-click on Project and select Properties. Then navigate to the Debug tab. Lastly, specify the Launch Browser value as swagger as shown in Figure 2.

swagger aspnet core fig 2 IDG

Figure 2: Setting the launch URL to Swagger. 

When you run the application again and navigate to the Swagger URL, you should see the Swagger UI as shown in Figure 3 below. Note the XML comments in each of the API methods this time.

swagger aspnet core fig 3 IDG

Figure 3: The Swagger UI displaying XML comments for the controller’s action methods. 

Swashbuckle is a great tool for generating Swagger documents for your API. Most importantly, Swashbuckle is easy to configure and use. There is much more you can do with Swagger than we’ve seen here. You can customize the Swagger UI using Cascading Style Sheets, show enum values as string values, and create different Swagger documents for different versions of your API, just to name a few.

Copyright © 2019 IDG Communications, Inc.