How To Use Swagger With ASP.NET Core Web APIs

ASP.NET Core

If you are developer, tester or a manager, sometimes understanding the various methods of API can be a challenge when building and consuming the application.

Generating good documentation and help pages for your Web API, using Swagger with .NET Core is as easy as adding a couple of NuGet and modifying the Startup.cs

Let’s start downloading simple To-do projects from Github.

  1. Download and run below TodoMvcSolution from below link.
    https://github.com/SmartITAz/TodoMvcSolution

    ASP.NET Core
  1. NuGet Packages
    Install the below NuGet package
    Install-Package Swashbuckle.AspNetCore
Configure Swagger in the Startup.cs

Add the Swagger generator to the service collection after services.AddMvc();

Enable the middleware for serving the generated JSON document after app.UseStaticFiles();

Add the below background yellow lines in your  Startup file.

  1. using Microsoft.AspNetCore.Builder;  
  2. using Microsoft.AspNetCore.Hosting;  
  3. using Microsoft.Extensions.Configuration;  
  4. using Microsoft.Extensions.DependencyInjection;  
  5. using Swashbuckle.AspNetCore.Swagger;  
  6.   
  7. namespace Todo.Mvc.Ui  
  8. {  
  9.   public class Startup  
  10.   {  
  11.     public Startup(IConfiguration configuration)  
  12.     {  
  13.       Configuration = configuration;  
  14.     }  
  15.   
  16.     public IConfiguration Configuration { get; }  
  17.   
  18.     // This method gets called by the runtime. Use this method to add services to the container.  
  19.     public void ConfigureServices(IServiceCollection services)  
  20.     {  
  21.       services.AddMvc();  
  22.   
  23.       // Register the Swagger generator, defining one or more Swagger documents  
  24.       services.AddSwaggerGen(c =>  
  25.       {  
  26.         c.SwaggerDoc("v1"new Info { Title = "My API", Version = "v1" });  
  27.       });  
  28.     }  
  29.   
  30.     // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.  
  31.     public void Configure(IApplicationBuilder app, IHostingEnvironment env)  
  32.     {  
  33.       if (env.IsDevelopment())  
  34.       {  
  35.         app.UseDeveloperExceptionPage();  
  36.         app.UseBrowserLink();  
  37.       }  
  38.       else  
  39.       {  
  40.         app.UseExceptionHandler("/Home/Error");  
  41.       }  
  42.   
  43.       app.UseStaticFiles();  
  44.   
  45.       // Enable middleware to serve generated Swagger as a JSON endpoint.  
  46.       app.UseSwagger();  
  47.   
  48.       // Enable middleware to serve swagger-ui (HTML, JS, CSS, etc.), specifying the Swagger JSON endpoint.  
  49.       app.UseSwaggerUI(c =>  
  50.       {  
  51.         c.SwaggerEndpoint("/swagger/v1/swagger.json""My API V1");  
  52.       });  
  53.   
  54.   
  55.       app.UseMvc(routes =>  
  56.       {  
  57.         routes.MapRoute(  
  58.                   name: "default",  
  59.                   template: "{controller=Todo}/{action=Index}/{id?}");  
  60.       });  
  61.     }  
  62.   }  
  63. }  
Go to  http://localhost:63274/swagger/

 

Note

Your local port number may be different than ours, use your local port number.

ASP.NET Core

Click on Try it out and you will see the response in Response body section.

ASP.NET Core

Here is the Web API

  1. //Copyright 2017 (c) SmartIT. All rights reserved.  
  2. //By John Kocer  
  3. // This file is for Swagger test, this application does not use this file  
  4. using System.Collections.Generic;  
  5. using Microsoft.AspNetCore.Mvc;  
  6. using SmartIT.Employee.MockDB;   
  7.   
  8. namespace TodoAngular.Ui.Controllers  
  9. {  
  10.   [Produces("application/json")]  
  11.   [Route("api/Todo")]  
  12.   public class TodoApiController : Controller  
  13.   {  
  14.     TodoRepository _todoRepository = new TodoRepository();  
  15.   
  16.     [Route("~/api/GetAllTodos")]  
  17.     [HttpGet]  
  18.     public IEnumerable<SmartIT.Employee.MockDB.Todo> GetAllTodos()  
  19.     {  
  20.       return _todoRepository.GetAll();  
  21.     }  
  22.   
  23.     [Route("~/api/AddTodo")]  
  24.     [HttpPost]  
  25.     public SmartIT.Employee.MockDB.Todo AddTodo([FromBody]SmartIT.Employee.MockDB.Todo item)  
  26.     {  
  27.       return _todoRepository.Add(item);  
  28.     }  
  29.   
  30.     [Route("~/api/UpdateTodo")]  
  31.     [HttpPut]  
  32.     public SmartIT.Employee.MockDB.Todo UpdateTodo([FromBody]SmartIT.Employee.MockDB.Todo item)  
  33.     {  
  34.       return  _todoRepository.Update(item);  
  35.     }  
  36.   
  37.     [Route("~/api/DeleteTodo/{id}")]  
  38.     [HttpDelete]  
  39.     public void Delete(int id)  
  40.     {  
  41.       var findTodo = _todoRepository.FindById(id);  
  42.       if (findTodo != null)  
  43.         _todoRepository.Delete(findTodo);  
  44.     }  
  45.   }  

NOTE

We have two controller files, TodoController and TodoApiController. TodoController is MVC Controller and Swagger did not show the API methods, because it does not know how to route and also  controller methods return a View.

  1. public class TodoController : Controller  
  2. {  
  3.   TodoRepository _todoRepository = new TodoRepository();  
  4.   // GET: Todo  
  5.   public ActionResult Index()  
  6.   {  
  7.     var todos = (List<SmartIT.Employee.MockDB.Todo>)_todoRepository.GetAll();  
  8.     return View(todos);  
  9.   }  
  10.   
  11.   // GET: Todo/Details/5  
  12.   public ActionResult Details(int id)  
  13.   {  
  14.     var findTodo = _todoRepository.FindById(id);  
  15.     return View(findTodo);  
  16.   }  
  17.   
  18.   // GET: Todo/Create  
  19.   public ActionResult Create()  
  20.   {  
  21.     return View();  
  22.   }  
  23.   
  24.   // POST: Todo/Create  
  25.   [HttpPost]  
  26.   [ValidateAntiForgeryToken]  
  27.   public ActionResult Create(IFormCollection collection)  
  28.   {  
  29.     try  
  30.     {  
  31.       _todoRepository.Add(new SmartIT.Employee.MockDB.Todo() { Name = collection["Name"] });  
  32.   
  33.       return RedirectToAction(nameof(Index));  
  34.     }  
  35.     catch  
  36.     {  
  37.       return View();  
  38.     }  
  39.   }  

Summary

In this article, we learned,

NOTE

If you need to copy and paste the code download the pdf file locally.

Download source code from GitHub.

Next Recommended Readings