Adding Swagger Helper Page in a .NET Core WEB API Project

We have Helper page, which we know that allows us to see and manage endpoints in our service application, but testing on this page at the same time by seeing our methods, sending them back, and seeing the models that will return to us will make our work much easier. In this article, we will see how a library, Swagger, that can fulfill this requirement, has added and worked on our Web API application written in Asp.Net Core. First of all, this package library needs to be added to our project:

Swashbuckle.AspNetCore

We then go to the Startup.cs file of our project and write our code to implement swagger interface definition. In the ConfigureServices method:

The reason for specifying Authorization here is that we can easily control the swagger interface with our authorization mechanism, if we use it when posting or retrieving data. Also in our Configure method Swagger needs to be added to the request pipeline in order to expose the Swagger generated data:
Then, right click on my project, check Generate xml documentation in the Compiler section under the Build section.

 

Output will be like this:

 

 

Possible Errors:

Possible solutions to the

Failed to Load API Definition error:

  1. Forgetting write [HttpPost] or [HttpGet]  attributes top of the IActionResult, one of the reason of this error. If we want ignore some of our methods, we should add this:

[ApiExplorerSettings(IgnoreApi = true)]

  1. Activate Access-Control-Allow-Origin header.
  2. Adding UseCors(“SiteCorsPolicy”); line in to Configure method.
  3. In Configure method add Swagger in if block.

Download my sample swagger GitHub project here.

Recommendation:  Checking out the GitHub page for the project.

Leave a Reply

Your email address will not be published. Required fields are marked *