Swagger In .NET Core

In this section, we will explore all about Swagger in .net core as follows:

  1. What is Swagger
  2. Package installation
  3. Swagger middleware
  4. API information and description
  5. XML Documentation
  6. Response Types
  7. Custom swagger UI

So before I get into Swagger, I would like to explain how to create a sample project from Visual Studio,

Please follow the steps given as follows:

  1. Open Visual Studio and select “Create new project.
  2. Select ASP.Net Core Web Application from the templates displayed.
  3. Choose the name and location for your new project and click on create button.
  4. Select .Net Core 2.2 (or later) from the drop-down list at the top.
  5. Please API for project template to create a new project.

Now I am assuming that you have created your sample project.

What is Swagger?

Swagger is an open source API documentation that helps us to understand API service methods.

When we consume a web API, then understanding its various methods and verbs can be challenging for a developer.  This solves the problem of generating documentation.  It's also known as OpenAPI.

There are three core components of it,

  • Swashbuckle.AspNetCore.Swagger: A Swagger object model expose SwaggerDocument objects in JSON.
  • Swashbuckle.SwaggerGen: It provides the functionality to generate JSON Swagger.
  • Swashbuckle.SwaggerUI: The Swagger UI tool uses the above documents for a rich customization for describing the Web API functionality.

Package installation

There are 2 ways that you can install packages.

  • Package Manager Console

Go to tools > Nuget Package Manager > Package Manager Console

Navigate to the directory in which your file exists.

Execute the following command:

Install-Package Swashbuckle.AspNetCore -Version 5.5.0

Swagger In .NET Core

NuGet Packages dialog

In Visual Studio,

Right click your project in Solution Explorer > Manage NuGet Packages

Enter Swashbuckle in the search box

Set the Package source to nuget.org

Select Swashbuckle package and then Install

After installation, you will be able to see Swashbuckle.AspNetCore package under dependencies as it is.

Swagger In .NET Core

Swagger middleware

Now to configure Swagger middleware in our application, write the following code in the ConfigureServices method in startup.cs class file.

services.AddSwaggerGen(); 

In the Startup.Configure method, here we will enable the Swagger middleware JSON document and the Swagger UI:

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

These are all steps required to get started with Swagger.

Now run your application and the Swagger UI can be found at http://localhost:<port>/swagger as images attached.

Swagger In .NET Core

API information and description

If we want to get more configuration action passed to the AddSwaggerGen method then we need to add information such as the author, license, and description and in the Startup class, we need to import the following namespace,

using Microsoft.OpenApi.Models;  
services.AddSwaggerGen(c => {  
    c.SwaggerDoc("v1", new OpenApiInfo {  
        Version = "v1",  
            Title = "Test API",  
            Description = "A simple example for swagger api information",  
            TermsOfService = new Uri("https://example.com/terms"),  
            Contact = new OpenApiContact {  
                Name = "Your Name XYZ",  
                    Email = "[email protected]",  
                    Url = new Uri("https://example.com"),  
            },  
            License = new OpenApiLicense {  
                Name = "Use under OpenApiLicense",  
                    Url = new Uri("https://example.com/license"),  
            }  
    });  
}); 

The above added content we can get here in Swagger UI.

Swagger In .NET Core

We can get the swagger json in this place.

https://localhost:5001/swagger/v1/swagger.json  

XML Documentation

In case of XML documentation we need enable XML comments. Rght click on the project in Visual Studio and select Properties > Build and then check the XML Documentation file box under the Output Settings section.

Swagger In .NET Core

Enable comments in any controller.

The Swagger UI displays the inner text in which we will add code  in<summary> element,

// GET api/values    
/// <summary>    
/// ValuesController Api Get method    
/// </summary>    
/// <returns></returns>    
[HttpGet]  
public ActionResult < IEnumerable < string >> Get() {  
    return new string[] {  
        "value1",  
        "value2"  
    };  
}

Please refer to the image:

Swagger In .NET Core

Complete code of configure service method:

public void ConfigureServices(IServiceCollection services) {  
    services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2);  
    services.AddSwaggerGen(c => {  
        c.SwaggerDoc("v1", new OpenApiInfo {  
            Version = "v1",  
                Title = "Test API",  
                Description = "A simple example for swagger api information",  
                TermsOfService = new Uri("https://example.com/terms"),  
                Contact = new OpenApiContact {  
                    Name = "Your Name XYZ",  
                        Email = "[email protected]",  
                        Url = new Uri("https://example.com"),  
                },  
                License = new OpenApiLicense {  
                    Name = "Use under OpenApiLicense",  
                        Url = new Uri("https://example.com/license"),  
                }  
        });  
        // Set the comments path for the Swagger JSON and UI.    
        var xmlFile = $ "{Assembly.GetExecutingAssembly().GetName().Name}.xml";  
        var xmlPath = Path.Combine(AppContext.BaseDirectory, xmlFile);  
        c.IncludeXmlComments(xmlPath);  
    });  
}

Response Types

The users who use our APIs are generally more interested to know what it returns --  the response types and error codes.

So I thought that it is very important to explain how we can do it in the documentation.

These are denoted using XML comments & data annotations.

Add a <remarks> element to the Create action method documentation.

You can add the following code to check for for documentation like remarks, response, pram etc...

/// <summary>    
/// Creates a TodoItem.    
/// </summary>    
/// <remarks>    
/// Sample request:    
///    
/// POST /Todo    
/// {    
/// "id": 1,    
/// "name": "Item1",    
/// "isComplete": true    
/// }    
///    
/// </remarks>    
/// <param name="name"></param>    
/// <returns>A newly created TodoItem</returns>    
/// <response code="201">Returns the newly created item</response>    
/// <response code="400">If the item is null</response>    
[HttpPost]  
[Route("CreateItem")]  
[ProducesResponseType(StatusCodes.Status201Created)]  
[ProducesResponseType(StatusCodes.Status400BadRequest)]  
public ActionResult Create(string name, TodoItem item) {  
    return CreatedAtRoute("GetTodo", new {  
        id = item.Id  
    }, item);  
}

This XML kind of text will reflect in the Responses section:

Custom swagger UI

As a default, Swagger is very good to see. But we can also customize it If we want to.

In this case, we need to add static file middleware in the Configure() method in Startup.cs file

app.UseStaticFiles();

Then we need to create our own custom css file inside the wwwroot folder.

Create your custom CSS:

.swagger-ui .topbar {  
   background-color: cornflowerblue;  
   border-bottom: 6px solid black ;  
}

Add Indext.html file as well and this css file.

<!DOCTYPE html>  
<html>  
    <head>  
        <meta charset="utf-8" />  
        <title></title>  
        <link href="StyleSheet1.css" rel="stylesheet" />  
    </head>  
    <body></body>  
</html> 

Add in configure method as well.

public void Configure(IApplicationBuilder app, IHostingEnvironment env) {  
    if (env.IsDevelopment()) {  
        app.UseDeveloperExceptionPage();  
    } else {  
        // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.    
        app.UseHsts();  
    }  
    app.UseStaticFiles();  
    app.UseSwagger();  
    app.UseSwaggerUI(c => {  
        c.SwaggerEndpoint("/swagger/v1/swagger.json", "My Test1 Api v1");  
        c.InjectStylesheet("/StyleSheet1.css");  
    });  
    app.UseHttpsRedirection();  
    app.UseMvc();  
}

You will see this kind of Swagger. Please see the images:

Swagger In .NET Core

Thank you for taking your valuable time to read the full article.


Similar Articles