Search This Blog

Saturday 8 December 2018

Adding Swagger to ASP.NET Web API

Step 1: - Open Visual Studio 2015 => Go to File Menu => New => Project...

Step 2: - In the Installed Templates list, select Visual C# => Web

Step 3: - Select ASP.Net Web Application (.NET Framework) from the Web list => Type SwaggerDemo in the Name box and click OK

Step 4: - Select Empty template from ASP.NET Templates List and Check Web API check box under Add folders and core references for:






























Step 5: - Right Click on Controllers folder => Add => Controller... => Select Web API Controller - Empty => Click Add => Type DefaultController in Controller Name box => Click Add




























Copy Past following code in DefaultController

/// <summary>
/// I'm Action1
/// </summary>
/// <returns>I'm Action1</returns>
[HttpGet]
public HttpResponseMessage Action1()
{
    return Request.CreateResponse(HttpStatusCode.OK, "I'm Action1");
}
/// <summary>
/// I'm Action2
/// </summary>
/// <returns>I'm Action2</returns>
[HttpGet]
public HttpResponseMessage Action2()
{
    return Request.CreateResponse(HttpStatusCode.OK, "I'm Action2");
}
/// <summary>
/// I'm Action3
/// </summary>
/// <returns>I'm Action3</returns>
[HttpGet]
public HttpResponseMessage Action3()
{
    return Request.CreateResponse(HttpStatusCode.OK, "I'm Action3");
}

Step 6: - Right click on References => Click on Manage NuGet Packages... => Click on Browse => Search "Swagger" => Select "Swashbuckle" from result => Click on Install























Step 7: - Open/Expand App_Start folder => Open SwaggerConfig.cs file => Add following line to enable Xml Comments description in swagger documentation

c.IncludeXmlComments(String.Format(@"{0}\bin\SwaggerDemo.XML", AppDomain.CurrentDomain.BaseDirectory));






















Step 8: - Right Click on Project Root folder => Click on Properties => Select "Build" => Under Output section Check checkbox "XML documentation file:" => Press Ctrl + S to save file























Step 9: - Open/Expand App_Start folder => Open WebApiConfig.cs file => Change following line 

config.Routes.MapHttpRoute(
    name: "DefaultApi",
    routeTemplate: "api/{controller}/{id}",
    defaults: new { id = RouteParameter.Optional }
);

To

config.Routes.MapHttpRoute(
    name: "DefaultApi",
    routeTemplate: "api/{controller}/{action}/{id}",
    defaults: new { id = RouteParameter.Optional }
);

All Done

Run Project

Step 10: - Enter swagger at the end of URL and Click on Enter






1 comment:

  1. Hi can you provide details of implementing multiversion in swagger having same swagger ui documentation.

    ReplyDelete