What Is Swagger In .NET Core And Its Implementation?

Swagger in .Net Core

  1. Swagger is an open-source software framework that helps developers design, build, document, and consume RESTful Web API.
  2. Swagger is popular for its Swagger UI which allows developers to test their Web APIs.
  3. Swagger toolset supports automated documentation, code generation, and automated testing including test cases

Here are the steps, below, required to integrate Swagger UI in.NET Core.

Step 1. Create .Net Core WebAPI project in Visual Studio 2017.

Step 2

Install Swashbuckle.AspNetCore package from NuGet

Step 3. We need to add the below two methods in the Startup.cs class.

The details of these methods are below.

Configure()
ConfigureServices()

Step 4. LaunchSettings.json

Step 5. Add Route to Controller

Configure () Method

Add the below code in the Configure() method.

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

Note. Swagger Endpoint has the following parameters.

  1. Url: “/swagger/v1/swagger.json”
  2. swagger: It should be swagger because we have to configure this name in the launchSettings.json file.
  3. v1: The folder which is created dynamically with this(v1) name.
  4. swagger.json: This file is generated dynamically inside the v1 folder.

ConfigureService() Method

Add the below code in the ConfigureService () method.

services.AddSwaggerGen(c =>
{
    c.SwaggerDoc("v1", new Info
    {
        version = "v1",
        title = "MyAPI",
        description = "Testing"
    });
});

launchSettings.json

Add “swagger” in the launcher instead of IIS Express.

"profiles": {
   "IIS Express": {
      "commandName": "IISExpress",
      "launchBrowser": true,
      "launchUrl": "swagger",
      "environmentVariables": {
         "ASPNETCORE_ENVIRONMENT": "Development"
      }
   }
}

Add Route to Controller.json

Add Route Attribute in each API method.

[HttpGet]
[Route("api/values/list")]
public ActionResult Get() { }

Sample Swagger UI

Now, when you build and use your MVC project, you have /Swagger/ (see below) available for your project that can be used to test your API without writing any additional code.

API

Summary

I hope you understood this article. We have implemented the Swagger concept in .Net Core.