Introduction

In this article, we will learn how to document our already existing APIs with .Net and.Net Core. Many developers absolutely deplore writing documentation. It's boring to put all these things together in a document by manually writing them. To overcome this we have Swagger to implement documentation and it's an open-source API documentation tool.
Packages required to configure Swagger,
  1. Swashbuckle.AspNetCore (latest version) - This package adds Swagger and Swagger UI and other libraries to make it easy for us to create API documentation.
Step 1
After installing the package to the respective project, here I am sharing the screenshot for your reference if you are new to Swagger in ASP.Net Core
Step 2 - Setup
We need to enable our project to generate XML comments. The comments come from Triple-slash (///) comments throughout the code.
First, in the project properties, check the box labeled "Generate XML Documentation"
Right Click on the Solution and click on the Properties
You will probably also want to suppress warning 1591, which will now give warnings about any method, class, or field that doesn't have triple-slash comments.
Step 3 - Configure Swagger
Startup.cs
  1. using Microsoft.AspNetCore.Builder;
  2. using Microsoft.AspNetCore.Hosting;
  3. using Microsoft.AspNetCore.HttpsPolicy;
  4. using Microsoft.AspNetCore.Mvc;
  5. using Microsoft.Extensions.Configuration;
  6. using Microsoft.Extensions.DependencyInjection;
  7. using Microsoft.Extensions.Hosting;
  8. using Microsoft.Extensions.Logging;
  9. using Microsoft.OpenApi.Models;
  10. using System;
  11. using System.Collections.Generic;
  12. using System.IO;
  13. using System.Linq;
  14. using System.Reflection;
  15. using System.Threading.Tasks;
  16. namespace Swagger
  17. {
  18. public class Startup
  19. {
  20. public Startup(IConfiguration configuration)
  21. {
  22. Configuration = configuration;
  23. }
  24. public IConfiguration Configuration { get; }
  25. // This method gets called by the runtime. Use this method to add services to the container.
  26. public void ConfigureServices(IServiceCollection services)
  27. {
  28. services.AddControllers();
  29. services.AddSwaggerGen(swagger =>
  30. {
  31. swagger.SwaggerDoc("v1", new OpenApiInfo
  32. {
  33. Version = "v1",
  34. Title = "Swagger Document API's",
  35. Description = $"Document your already existing API's with Swagger \r\n\r\n © Copyright {DateTime.Now.Year}. All rights reserved."
  36. });
  37. #region XMl Documentation
  38. var xmlFile = $"{Assembly.GetExecutingAssembly().GetName().Name}.xml";
  39. var xmlPath = Path.Combine(AppContext.BaseDirectory, xmlFile);
  40. swagger.IncludeXmlComments(xmlPath);
  41. #endregion
  42. });
  43. }
  44. // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
  45. public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
  46. {
  47. if (env.IsDevelopment())
  48. {
  49. app.UseDeveloperExceptionPage();
  50. }
  51. app.UseHttpsRedirection();
  52. app.UseRouting();
  53. app.UseAuthorization();
  54. app.UseEndpoints(endpoints =>
  55. {
  56. endpoints.MapControllers();
  57. });
  58. app.UseSwagger();
  59. app.UseSwaggerUI(o =>
  60. {
  61. o.SwaggerEndpoint("/swagger/v1/swagger.json", "Swagger");
  62. });
  63. }
  64. }
  65. }
launchSettings.json
  1. {
  2. "$schema": "http://json.schemastore.org/launchsettings.json",
  3. "iisSettings": {
  4. "windowsAuthentication": false,
  5. "anonymousAuthentication": true,
  6. "iisExpress": {
  7. "applicationUrl": "http://localhost:62614",
  8. "sslPort": 44380
  9. }
  10. },
  11. "profiles": {
  12. "IIS Express": {
  13. "commandName": "IISExpress",
  14. "launchBrowser": true,
  15. "launchUrl": "swagger/index.html",
  16. "environmentVariables": {
  17. "ASPNETCORE_ENVIRONMENT": "Development"
  18. }
  19. },
  20. "Swagger": {
  21. "commandName": "Project",
  22. "launchBrowser": true,
  23. "launchUrl": "swagger/index.html",
  24. "applicationUrl": "https://localhost:5001;http://localhost:5000",
  25. "environmentVariables": {
  26. "ASPNETCORE_ENVIRONMENT": "Development"
  27. }
  28. }
  29. }
  30. }
XML Comments
In our XML Comments for methods.
WeatherController.cs
  1. using Microsoft.AspNetCore.Mvc;
  2. using Microsoft.Extensions.Logging;
  3. using System;
  4. using System.Collections.Generic;
  5. using System.ComponentModel.DataAnnotations;
  6. using System.Linq;
  7. using System.Threading.Tasks;
  8. namespace Swagger.Controllers
  9. {
  10. [ApiController]
  11. [Route("[controller]")]
  12. public class WeatherForecastController : ControllerBase
  13. {
  14. private static readonly string[] Summaries = new[]
  15. {
  16. "Freezing", "Bracing", "Chilly", "Cool", "Mild", "Warm", "Balmy", "Hot", "Sweltering", "Scorching"
  17. };
  18. private readonly ILogger<WeatherForecastController> _logger;
  19. public WeatherForecastController(ILogger<WeatherForecastController> logger)
  20. {
  21. _logger = logger;
  22. }
  23. /// <summary>
  24. /// Weather Forecast Get Method
  25. /// </summary>
  26. /// <returns>Json Data</returns>
  27. [HttpGet]
  28. public IEnumerable<WeatherForecast> Get()
  29. {
  30. var rng = new Random();
  31. return Enumerable.Range(1, 5).Select(index => new WeatherForecast
  32. {
  33. Date = DateTime.Now.AddDays(index),
  34. TemperatureC = rng.Next(-20, 55),
  35. Summary = Summaries[rng.Next(Summaries.Length)]
  36. })
  37. .ToArray();
  38. }
  39. /// <summary>
  40. /// Post method in weather controller.
  41. /// </summary>
  42. /// <remarks>
  43. /// Here is the sample to show remarks
  44. /// </remarks>
  45. /// <param name="Id">Pass the Id</param>
  46. /// <returns>Returns a Post Message</returns>
  47. [HttpPost]
  48. public IActionResult Post([Required] int Id)
  49. {
  50. return Ok();
  51. }
  52. }
  53. }
Here are XML nodes in use:
  • Summary: A high-level summary of what are method /class/field is or does.
  • remarks: Additional detail about the method/class/field
  • param: A parameter to the method, and what it represents
  • returns: A description of what the method returns.
Output - View Swagger
Here is a clear description of what is what in Swagger UI
Github URL: Swagger
Thanks for reading this article, Hope this article helps you!!!
Keep Learning.... !!!