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.
- Download and run below TodoMvcSolution from below link.
https://github.com/SmartITAz/TodoMvcSolution
- NuGet Packages
Install the below NuGet package
Install-Package Swashbuckle.AspNetCore
Configure Swagger in the Startup.csAdd 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.
- using Microsoft.AspNetCore.Builder;
- using Microsoft.AspNetCore.Hosting;
- using Microsoft.Extensions.Configuration;
- using Microsoft.Extensions.DependencyInjection;
- using Swashbuckle.AspNetCore.Swagger;
-
- namespace Todo.Mvc.Ui
- {
- public class Startup
- {
- public Startup(IConfiguration configuration)
- {
- Configuration = configuration;
- }
-
- public IConfiguration Configuration { get; }
-
-
- public void ConfigureServices(IServiceCollection services)
- {
- services.AddMvc();
-
-
- services.AddSwaggerGen(c =>
- {
- c.SwaggerDoc("v1", new Info { Title = "My API", Version = "v1" });
- });
- }
-
-
- public void Configure(IApplicationBuilder app, IHostingEnvironment env)
- {
- if (env.IsDevelopment())
- {
- app.UseDeveloperExceptionPage();
- app.UseBrowserLink();
- }
- else
- {
- app.UseExceptionHandler("/Home/Error");
- }
-
- app.UseStaticFiles();
-
-
- app.UseSwagger();
-
-
- app.UseSwaggerUI(c =>
- {
- c.SwaggerEndpoint("/swagger/v1/swagger.json", "My API V1");
- });
-
-
- app.UseMvc(routes =>
- {
- routes.MapRoute(
- name: "default",
- template: "{controller=Todo}/{action=Index}/{id?}");
- });
- }
- }
- }
Go to
http://localhost:63274/swagger/
Note
Your local port number may be different than ours, use your local port number.
Click on Try it out and you will see the response in Response body section.
Here is the Web API
-
-
-
- using System.Collections.Generic;
- using Microsoft.AspNetCore.Mvc;
- using SmartIT.Employee.MockDB;
-
- namespace TodoAngular.Ui.Controllers
- {
- [Produces("application/json")]
- [Route("api/Todo")]
- public class TodoApiController : Controller
- {
- TodoRepository _todoRepository = new TodoRepository();
-
- [Route("~/api/GetAllTodos")]
- [HttpGet]
- public IEnumerable<SmartIT.Employee.MockDB.Todo> GetAllTodos()
- {
- return _todoRepository.GetAll();
- }
-
- [Route("~/api/AddTodo")]
- [HttpPost]
- public SmartIT.Employee.MockDB.Todo AddTodo([FromBody]SmartIT.Employee.MockDB.Todo item)
- {
- return _todoRepository.Add(item);
- }
-
- [Route("~/api/UpdateTodo")]
- [HttpPut]
- public SmartIT.Employee.MockDB.Todo UpdateTodo([FromBody]SmartIT.Employee.MockDB.Todo item)
- {
- return _todoRepository.Update(item);
- }
-
- [Route("~/api/DeleteTodo/{id}")]
- [HttpDelete]
- public void Delete(int id)
- {
- var findTodo = _todoRepository.FindById(id);
- if (findTodo != null)
- _todoRepository.Delete(findTodo);
- }
- }
- }
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.
- public class TodoController : Controller
- {
- TodoRepository _todoRepository = new TodoRepository();
-
- public ActionResult Index()
- {
- var todos = (List<SmartIT.Employee.MockDB.Todo>)_todoRepository.GetAll();
- return View(todos);
- }
-
-
- public ActionResult Details(int id)
- {
- var findTodo = _todoRepository.FindById(id);
- return View(findTodo);
- }
-
-
- public ActionResult Create()
- {
- return View();
- }
-
-
- [HttpPost]
- [ValidateAntiForgeryToken]
- public ActionResult Create(IFormCollection collection)
- {
- try
- {
- _todoRepository.Add(new SmartIT.Employee.MockDB.Todo() { Name = collection["Name"] });
-
- return RedirectToAction(nameof(Index));
- }
- catch
- {
- return View();
- }
- }
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.