Today we’ll look at how to spice up Swagger’s documentation using annotations in ASP .NET Core.
Continuing the first part of the article, we will now see how to generate the documentation without generating the XML file.
Let’s create a new Web API project called DemoSeagger2 using the same settings as in the previous article.
This can be done in Visual Studio 2022 or using the NET CLI with VS Code through the command:
dotnet new webapi -o DemoSwagger2
Using Swashbuckle annotations
Let’s start by setting the configuration enabling annotations without including the reference to the XML file.
To be able to take notes, let’s include the Swashbucle.AspNetCore.Annotations package in our project:
dotnet add package Swashbuckle.AspNetCore.Annotations
Next, let’s enable the use of annotations in the project:
Now let’s provide some documentation for our API by changing the controller’s GetWeatherForecast endpoint code using the SwaggerOperation attribute as below:
In addition, we can provide the API client with information such as possible HTTP status codes and their response body. For this, we will use the SwaggerResponse attribute and define, by way of example, that the API endpoint can return its five possible HTTP status codes (200, 400, 409, 500, and 503).
Next, let’s add documentation on the WeatherForecast class used as a domain model in the project using the SwaggerSchema attribute:
We can also define the appropriate consumption and production media types by decorating our controller with the [Consumes] and [Produces] attributes by setting the application/json value:
Now let’s run our project and see the result:
We thus have a simple way to include documentation without using XML files.
Get the project here: DemoSwagger2.zip (without references)
“My little children, I write these things to you so that you may not sin. But if anyone sins, we have an intercessor with the Father, Jesus Christ the righteous.”
1 John 2:1
*The content of this article is the author’s responsibility and does not necessarily reflect the opinion of iMasters.