Saturday, January 28, 2017

Adding Swagger to an ASP.NET Web API 2 app that uses .NET Framework 4.5.2

Swagger is an API specification framework. It reminds me of WSDL in the SOAP days. In this article I will guide you in add Swagger documentation to an ASP.NET Core Web API app.

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.


image

5. On the next dialog, choose Web API, uncheck “Host in the cloud”, then click OK.

image

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:

image

8. Run the following command in the “Package Manager Console” in Visual Studio:

Install-Package Swashbuckle

9. The next step is to enable XML documentation in your web application. Right-click on the web app project node in Solution Explorer and choose Properties.

image

10. In the Build tab, enable “XML documentation file” in the Output section.

image

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));

Note that the filename is what you had previously pasted in a text editor.

12. Build and run your application. Add /swagger to the URL address. You should see a page that looks like this:

image

Testing it out

Click on Values.

image

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