Configuring Swagger in ASP.NET Core Web API and deploying on Azure

Swagger is an open source framework, which helps to design, build, document, and consume RESTful APIs. There are many benefits of using swagger in an enterprise web application, which include the following:

  • It generates good documentation based on the XML comments specified in your .NET code
  • It supports Client SDK generation and discoverability

Swagger is configured out-of-the-box when we create an API App from the Azure portal, but when deploying APIs which are already created, we may not have this framework configured. We will see how to configure Swagger in an existing Web API developed on .NET Core, and deploy it as an API App on Azure in the next section.

Generating swagger documents in ASP.NET Core can be achieved using Swashbuckle, a .NET Core implementation. It has the following two components:

  • Swashbuckle.SwaggerGen: Generates JSON-based documentation of .NET Core Web API.
  • Swashbuckle.SwaggerUI: Generates UI-based documentation of .NET Core Web API.

We can start by adding a NuGet package, Swashbuckle. Make sure to select the prerelease option if the package is not available. Once this package is added, we have to add the Swagger service in the ConfigureServices method of the Startup class.

Add the following entry in the ConfigureServices method of the Startup class:

    services.AddSwaggerGen(options => 
{
options.SingleApiVersion(new Info
{
Version = "v1",
Title = "Hello World Swagger API",
Description = "API to Configure Swagger",
TermsOfService = "None"
});
});

Finally, enable Swagger middleware in the Configure method of the Startup class as follows:

    app.UseSwagger(); 
app.UseSwaggerUi();

Now, when we run the application or host it on Azure, we can access Swagger JSON by calling this URL: http://{websiteaddress}:{port}/swagger/v1/swagger.json.

Swagger UI can be accessed by calling the following URL:
http://{websiteaddress}:{portno}/swagger/ui.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.223.170.223