I will show you how to add Swagger documentation to an ASP.NET Web API 2 application that is running under .NET Framework 4.5.2.
Create a simple Web API application using Visual Studio 2015.
1. File >> New >> Project
2. Templates >> Visual C# >> Web
3. Choose “ASP.NET Web Application (.NET Framework) Visual C#”
4. Give your application a name like “WebApi2Swagger” then click on OK.
5. On the next dialog, choose Web API, uncheck “Host in the cloud”, then click OK.
6. Once the application template is created, open the Controllers/ValuesControllers.cs file and delete the [Authorize] annotation over the class declaration line.
7. Run the application by hitting CTRL + F5 on your keyboard. Add /api/values to the address line to see the sample API that is created by this template. It should look like this:
8. Run the following command in the “Package Manager Console” in Visual Studio:
Install-Package Swashbuckle
10. In the Build tab, enable “XML documentation file” in the Output section.
Copy the XML filename and paste it in a text editor so that you can use it later. In the above case, the filename is bin\WebAPI2Swagger.XML.
11. Open App_Start/SwaggerConfig.cs. Make the following change:
Find “//c.IncludeXmlComments(GetXmlCommentsPath());” around line 100. Right after this line, add the following code:
c.IncludeXmlComments(string.Format(@"{0}\bin\WebAPI2Swagger.XML",
System.AppDomain.CurrentDomain.BaseDirectory));
System.AppDomain.CurrentDomain.BaseDirectory));
12. Build and run your application. Add /swagger to the URL address. You should see a page that looks like this:
Testing it out
Click on Values.Click on the “GET” button.
Click on the “Try it out!” button. You should see the Curl command, Response Body, Response Code, and Response Headers.
Conclusion
Although this tutorial is very simplistic, the steps we went through equally applies to more complicated API objects.
No comments:
Post a Comment