Swagger Implementation In Asp.net core Web API
Sardar Mudassar Ali Khan
Posted on June 10, 2023
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
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
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;
});
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);
});
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
});
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.
Posted on June 10, 2023
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.