What Is Swagger In .NET Core And Its Implementation?

What is 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 that 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.
  1. Configure()
  2. ConfigureServices()
Step 4 
 
LaunchSettings.json
 
Step 5 - Add Route to Controller
 
Configure () Method
 
Add the below code in Configure() method.
  1. app.UseSwagger();        
  2. app.UseSwaggerUI(c=>      
  3. {      
  4.    c.SwaggerEndpoint(“/swagger/v1/swagger.json”,”MyAPI”);      
  5. });       
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 launchSettings.json file.
  3. v1 – The folder which is created dynamically with this(v1) name.
  4. swagger.json – This file generated dynamically inside the v1 folder.
ConfigureService() Method
 
Add the below code in ConfigureService () method.
  1. services.AddSwaggerGen(c=>    
  2.    {    
  3.       c.SwaggerDoc(“v1”,new Info    
  4.       {    
  5.          version = “v1”,    
  6.          title = “MyAPI”,    
  7.          description = “Testing”    
  8.       });    
  9.    });       
launchSettings.json
 
Add “swagger” in launchUrl instead of IIS Express.
  1. "profiles" : {    
  2.    "IIS Express" : {    
  3.       "commandName" : "IISExpress",    
  4.          "launchBrowser" : true,    
  5.          "launchUrl" : "swagger",    
  6.       "environmentVariables" : {    
  7.    "ASPNETCORE_ENVIRONMENT" : "Development"    
  8.       }    
  9.    }    
  10. }    
Add Route to Controller.json
 
Add Route Attribute in each API methods.
  1. [HttpGet]    
  2. [Route(“api/values/list”)]    
  3. 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.
 
 

Summary

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