DEV Community

Sardar Mudassar Ali Khan
Sardar Mudassar Ali Khan

Posted on

Swagger Implementation In Asp.net core Web API

To implement Swagger in an ASP.NET Core Web API, you need to follow these steps:

Step 1: Install the required NuGet packages

In your ASP.NET Core Web API project, you need to install the following NuGet packages:

Microsoft.AspNetCore.Mvc.Versioning
Swashbuckle.AspNetCore
Enter fullscreen mode Exit fullscreen mode

You can install these packages using the NuGet Package Manager in Visual Studio or by running the following command in the Package Manager Console:

Install-Package Microsoft.AspNetCore.Mvc.Versioning
Install-Package Swashbuckle.AspNetCore
Enter fullscreen mode Exit fullscreen mode

Step 2: Configure API versioning

In the ConfigureServices method of your Startup.cs file, add the following code to configure API versioning:

services.AddApiVersioning(options =>
{
    options.DefaultApiVersion = new ApiVersion(1, 0);
    options.AssumeDefaultVersionWhenUnspecified = true;
    options.ReportApiVersions = true;
});
Enter fullscreen mode Exit fullscreen mode

Step 3: Configure Swagger

In the ConfigureServices method of your Startup.cs file, add the following code to configure Swagger:

services.AddSwaggerGen(options =>
{
    options.SwaggerDoc("v1", new OpenApiInfo { Title = "Your API", Version = "v1" });

    // Add support for XML comments
    var xmlFile = $"{Assembly.GetExecutingAssembly().GetName().Name}.xml";
    var xmlPath = Path.Combine(AppContext.BaseDirectory, xmlFile);
    options.IncludeXmlComments(xmlPath);
});
Enter fullscreen mode Exit fullscreen mode

Step 4: Enable Swagger UI and Swagger JSON endpoints

In the Configure method of your Startup.cs file, add the following code to enable Swagger UI and Swagger JSON endpoints:

app.UseSwagger();
app.UseSwaggerUI(options =>
{
    options.SwaggerEndpoint("/swagger/v1/swagger.json", "Your API v1");
    options.RoutePrefix = string.Empty; // Set the Swagger UI at the root URL
});
Enter fullscreen mode Exit fullscreen mode

Step 5: Add XML comments to your API controllers

In your API controller classes, add XML comments to document your API endpoints and models. You can do this by enabling XML documentation generation for your project. Right-click on your project in Visual Studio, go to Properties, and in the Build tab, enable "XML documentation file".

Step 6: Run the application

Build and run your ASP.NET Core Web API application. You should now be able to access the Swagger UI at the root URL of your application (e.g., http://localhost:5000) and see the generated API documentation.

That's it! You have successfully implemented Swagger in your ASP.NET Core Web API. Swagger provides a user-friendly interface for exploring and testing your API endpoints.

Top comments (1)

Collapse
 
bhargav_vyas_b415a2170e8e profile image
Bhargav Vyas

Can you please update how I can use the swagger.json with the dist folder of the swagger to have a static documentation