Configuring Swagger Documentation for ASP.NET Core Web APIs

Project Initialization

To begin, launch Visual Studio and create a new project using the "ASP.NET Core Web Application" template. After naming the solution and selecting a location, choose the API template targeting .NET Core (specifically version 3.1). For simplicity in local testing, you may uncheck the "Configure for HTTPS" option found in the advanced settings.

Installing Dependencies

Navigate to the "Tools" menu and select "NuGet Package Manager" followed by "Manage NuGet Packages for Solution". Search for Swashbuckle.AspNetCore in the browse tab and install the package. This library contains the essential components for generating OpenAPI specifications and hosting the Swagger user interface.

Service Registration

Open the Startup.cs file to register the necessary services. In the ConfigureServices method, invoke AddSwaggerGen to define the API metadata and documentation structure.

public void ConfigureServices(IServiceCollection services)
{
    services.AddSwaggerGen(c =>
    {
        c.SwaggerDoc("v1", new OpenApiInfo
        {
            Title = "Inventory Service API",
            Version = "1.0",
            Description = "Interactive documentation for the core inventory endpoints"
        });
    });

    services.AddControllers();
}

Middleware Configuration

In the Configure method, insert the Swagger middleware into the application pipeline. This step enables the generation of the JSON specification and serves the UI. It is crucial to place these methods appropriately within the request execution flow.

public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
    if (env.IsDevelopment())
    {
        app.UseDeveloperExceptionPage();
    }

    app.UseSwagger();
    app.UseSwaggerUI(c =>
    {
        c.SwaggerEndpoint("/swagger/v1/swagger.", "Inventory Service V1");
    });

    app.UseRouting();

    app.UseAuthorization();

    app.UseEndpoints(endpoints =>
    {
        endpoints.MapControllers();
    });
}

Verification

Compile and execute the application. Once the host is running, access the Swagger UI by navigating to the /swagger relative path in your browser. The interactive documentation portal should load, displaying all available controllers and actions.

Tags: ASP.NET Core swagger Web API Swashbuckle

Posted on Sat, 09 May 2026 01:36:54 +0000 by mjm