Skip to main content
The Intent.AspNetCore.Swashbuckle module provides comprehensive OpenAPI (Swagger) documentation for your ASP.NET Core Web APIs using the Swashbuckle library. It automatically generates interactive API documentation that developers can use to explore and test your endpoints.

Overview

Swashbuckle generates OpenAPI 3.0 specifications from your ASP.NET Core controllers, providing an interactive UI where developers can:
  • Browse all available endpoints
  • View request/response schemas
  • Test API calls directly in the browser
  • Download the OpenAPI specification

What Gets Generated

SwashbuckleConfiguration

Configures Swagger in your application startup:
public static class SwashbuckleConfiguration
{
    public static IServiceCollection AddSwagger(this IServiceCollection services)
    {
        services.AddSwaggerGen(c =>
        {
            c.SwaggerDoc("v1", new OpenApiInfo
            {
                Title = "My API",
                Version = "v1",
                Description = "API documentation"
            });

            // Include XML comments
            var xmlFile = $"{Assembly.GetExecutingAssembly().GetName().Name}.xml";
            var xmlPath = Path.Combine(AppContext.BaseDirectory, xmlFile);
            if (File.Exists(xmlPath))
            {
                c.IncludeXmlComments(xmlPath);
            }

            // Custom operation filters
            c.OperationFilter<HideRouteParametersFromBodyOperationFilter>();
        });

        return services;
    }

    public static IApplicationBuilder UseSwaggerUI(this IApplicationBuilder app)
    {
        app.UseSwagger();
        app.UseSwaggerUI(c =>
        {
            c.SwaggerEndpoint("/swagger/v1/swagger.json", "My API V1");
            c.RoutePrefix = "swagger";
        });

        return app;
    }
}

Operation Filters

HideRouteParametersFromBodyOperationFilter: Prevents route parameters from appearing in request bodies:
public class HideRouteParametersFromBodyOperationFilter : IOperationFilter
{
    public void Apply(OpenApiOperation operation, OperationFilterContext context)
    {
        if (operation.Parameters == null)
            return;

        var routeParameters = context.ApiDescription.ParameterDescriptions
            .Where(p => p.Source == BindingSource.Path)
            .Select(p => p.Name)
            .ToHashSet();

        // Remove route parameters from request body schemas
        if (operation.RequestBody?.Content != null)
        {
            foreach (var content in operation.RequestBody.Content.Values)
            {
                if (content.Schema?.Properties != null)
                {
                    foreach (var param in routeParameters)
                    {
                        content.Schema.Properties.Remove(param);
                    }
                }
            }
        }
    }
}
TypeSchemaFilter: Customizes schema generation for specific types:
public class TypeSchemaFilter : ISchemaFilter
{
    public void Apply(OpenApiSchema schema, SchemaFilterContext context)
    {
        // Customize schema for specific types
        if (context.Type == typeof(DateTime))
        {
            schema.Example = new OpenApiString("2024-01-01T00:00:00Z");
        }
    }
}

Key Features

Interactive UI

Try out APIs directly in the browser

OpenAPI 3.0

Industry-standard API specifications

XML Comments

Include code documentation in Swagger

Schema Generation

Automatic request/response schema documentation

Module Settings

Mark Non-Nullable Fields as Required

Mark non-nullable fields as required
boolean
default:"true"
Automatically marks non-nullable reference types as required in the OpenAPI schema

Use Simple Schema Identifiers

Use simple schema identifiers
boolean
default:"false"
Simplifies schema identifiers from fully qualified type names to just the type nameExample:
  • false: MyApp.Api.Dtos.ProductDto
  • true: ProductDto

Generated API Documentation

The Swagger UI displays comprehensive documentation:

Endpoint Documentation

/// <summary>
/// Retrieves a product by ID
/// </summary>
/// <param name="id">The product identifier</param>
/// <param name="cancellationToken">Cancellation token</param>
/// <returns>The product details</returns>
/// <response code="200">Product found</response>
/// <response code="404">Product not found</response>
[HttpGet("{id}")]
[ProducesResponseType(typeof(ProductDto), StatusCodes.Status200OK)]
[ProducesResponseType(StatusCodes.Status404NotFound)]
public async Task<ActionResult<ProductDto>> GetById(
    [FromRoute] Guid id,
    CancellationToken cancellationToken)
{
    var result = await _service.GetByIdAsync(id, cancellationToken);
    return result != null ? Ok(result) : NotFound();
}
This appears in Swagger UI with:
  • Operation summary and description
  • Parameter details
  • Request/response examples
  • Status codes and their meanings

Schema Documentation

/// <summary>
/// Product data transfer object
/// </summary>
public class ProductDto
{
    /// <summary>
    /// Product unique identifier
    /// </summary>
    public Guid Id { get; set; }

    /// <summary>
    /// Product name
    /// </summary>
    [Required]
    [MaxLength(200)]
    public string Name { get; set; }

    /// <summary>
    /// Product price in USD
    /// </summary>
    [Range(0.01, 999999.99)]
    public decimal Price { get; set; }
}

XML Documentation

To include XML comments in Swagger:
  1. Enable XML documentation in your project file:
<PropertyGroup>
  <GenerateDocumentationFile>true</GenerateDocumentationFile>
  <NoWarn>$(NoWarn);1591</NoWarn>
</PropertyGroup>
  1. The module automatically configures Swashbuckle to read the XML file
  2. Add XML comments to your controllers and DTOs

Accessing Swagger UI

Once configured, access the Swagger UI at:
https://localhost:5001/swagger
The OpenAPI JSON specification is available at:
https://localhost:5001/swagger/v1/swagger.json

Security Integration

When Intent.Security.JWT is installed, Swashbuckle automatically adds authentication support:
services.AddSwaggerGen(c =>
{
    // ... other config ...

    c.AddSecurityDefinition("Bearer", new OpenApiSecurityScheme
    {
        Description = "JWT Authorization header using the Bearer scheme",
        Name = "Authorization",
        In = ParameterLocation.Header,
        Type = SecuritySchemeType.ApiKey,
        Scheme = "Bearer"
    });

    c.AddSecurityRequirement(new OpenApiSecurityRequirement
    {
        {
            new OpenApiSecurityScheme
            {
                Reference = new OpenApiReference
                {
                    Type = ReferenceType.SecurityScheme,
                    Id = "Bearer"
                }
            },
            Array.Empty<string>()
        }
    });
});
This adds an “Authorize” button in the Swagger UI where users can enter their JWT token.

Versioning Integration

When Intent.AspNetCore.Versioning is installed, Swagger displays multiple API versions:
services.AddSwaggerGen(c =>
{
    c.SwaggerDoc("v1", new OpenApiInfo { Title = "My API", Version = "v1" });
    c.SwaggerDoc("v2", new OpenApiInfo { Title = "My API", Version = "v2" });

    c.DocInclusionPredicate((version, apiDescription) =>
    {
        var versions = apiDescription.GetApiVersions();
        return versions.Any(v => $"v{v}" == version);
    });
});

Response Examples

Swagger automatically generates example responses:
{
  "id": "3fa85f64-5717-4562-b3fc-2c963f66afa6",
  "name": "Sample Product",
  "price": 29.99,
  "category": "Electronics",
  "inStock": true
}

Customizing Swagger UI

You can customize the Swagger UI appearance:
app.UseSwaggerUI(c =>
{
    c.SwaggerEndpoint("/swagger/v1/swagger.json", "My API V1");
    c.RoutePrefix = "api-docs"; // Change URL
    c.DocumentTitle = "My API Documentation";
    c.DefaultModelsExpandDepth(2);
    c.DefaultModelExpandDepth(2);
    c.DisplayRequestDuration();
    c.EnableDeepLinking();
    c.EnableFilter();
});

Alternative: Scalar

Consider using Intent.AspNetCore.Scalar for a modern alternative to Swagger UI with better performance and user experience.

Installation

Intent.AspNetCore.Swashbuckle
The module is automatically installed when:
  • Intent.AspNetCore is present
  • Intent.AspNetCore.Controllers is present

Dependencies

  • Intent.AspNetCore (>= 6.0.0)
  • Intent.Common.CSharp
  • Intent.Modelers.Services
  • Intent.OutputManager.RoslynWeaver

Integration Modules

Swashbuckle automatically integrates with:
  • Intent.Security.JWT - Adds JWT authentication UI
  • Intent.AspNetCore.Versioning - Multi-version API documentation
  • Intent.AspNetCore.Swashbuckle.Security - Enhanced security documentation

Next Steps

Scalar

Modern alternative to Swagger UI

Versioning

Document multiple API versions

Security

Add authentication to your API docs

Controllers

Generate documented controllers

Build docs developers (and LLMs) love