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:
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 solutions to the
Failed to Load API Definition error:
- 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)]
- Activate Access-Control-Allow-Origin header.
- Adding UseCors(“SiteCorsPolicy”); line in to Configure method.
- In Configure method add Swagger in if block.
Download my sample swagger GitHub project here.
Recommendation: Checking out the GitHub page for the project.