Swashbuckle.AspNetCore

repository·master·Indexed 26 days ago

https://github.com/domaindrivendev/swashbuckle.aspnetcore

An OpenAPI (Swagger) tooling library for ASP.NET Core applications that automatically generates OpenAPI documentation (supporting Swagger 2.0 and OpenAPI 3.0/3.1) from application code. It includes an embedded Swagger UI for interactive API exploration and testing, and supports the generation of client libraries via tools like swagger-codegen. The library consists of core components for generation (SwaggerGen), exposure (Swagger), and visualization (SwaggerUI), with additional extensions for annotations, CLI export, and ReDoc integration.

Tokens
17.8K
Snippets
69
Records
87
Agent score
83%

What's inside Swashbuckle.AspNetCore

  1. Overview of Swashbuckle.AspNetCore

    master
    Swashbuckle.AspNetCore is an OpenAPI (Swagger) tooling library for APIs built with ASP.NET Core. It automatically generates OpenAPI documentation (supporting Swagger 2.0 and OpenAPI 3.0/3.1) directly from your application code. It also includes an embedded version of Swagger UI, allowing you to explore and test your API operations through a web interface that stays in sync with your code. The generated OpenAPI documents can also be used with other tools like swagger-codegen to generate client libraries for various platforms.
  2. Understand Swashbuckle.AspNetCore core components

    master

    Swashbuckle.AspNetCore is composed of three core packages that work together to provide automatically generated API documentation. You can install them individually or use the Swashbuckle.AspNetCore metapackage to install all three at once.

    • Swashbuckle.AspNetCore.SwaggerGen: Generates OpenApiDocument instances from your application endpoints (controllers, minimal APIs, etc.) and provides an ISwaggerProvider implementation.
    • Swashbuckle.AspNetCore.Swagger: Exposes the generated OpenAPI JSON endpoints by querying the ISwaggerProvider from the DI container.
    • Swashbuckle.AspNetCore.SwaggerUI: Provides an interactive, embedded version of Swagger UI that consumes the OpenAPI JSON endpoints to display your documentation.
  3. Assign explicit operationIds to routes

    master

    In OpenAPI, an operationId must be unique across all operations. Swashbuckle.AspNetCore omits this by default. You can assign them using one of two methods:

    1. Decorate routes with a Name property: Use the Name property on HTTP verb attributes (e.g., [HttpGet]).
    2. Provide a custom strategy: Use options.CustomOperationIds in your AddSwaggerGen configuration to define a naming convention based on the ApiDescription.
    // Option 1: Decorate routes
    [HttpGet("{id}", Name = "GetProductById")]
    public IActionResult Get(int id)
    {
        return Ok();
    }
    
    // Option 2: Custom strategy in Startup.cs
    services.AddSwaggerGen(options =>
    {
        options.CustomOperationIds(apiDescription =>
        {
            return apiDescription.TryGetMethodInfo(out MethodInfo methodInfo) ? methodInfo.Name : null;
        });
    });
  4. Apply swagger-ui configuration parameters

    master

    Most swagger-ui configuration parameters are surfaced through the UseSwaggerUI options. Common examples include controlling model expansion depth, enabling filters, or enabling 'Try It Out' mode.

    app.UseSwaggerUI(options =>
    {
        options.DefaultModelExpandDepth(2);
        options.DefaultModelRendering(ModelRendering.Model);
        options.DefaultModelsExpandDepth(-1);
        options.DisplayOperationId();
        options.DisplayRequestDuration();
        options.DocExpansion(DocExpansion.None);
        options.EnableDeepLinking();
        options.EnableFilter();
        options.EnablePersistAuthorization();
        options.EnableTryItOutByDefault();
        options.MaxDisplayedTags(5);
        options.ShowExtensions();
        options.ShowCommonExtensions();
        options.EnableValidator();
        options.SupportedSubmitMethods(SubmitMethod.Get, SubmitMethod.Head);
        options.UseRequestInterceptor("(request) => { return request; }");
        options.UseResponseInterceptor("(response) => { return response; }");
    });
  5. Use a custom host configuration with the Swashbuckle CLI

    master

    By default, the CLI tool executes in a "default" web host. If your application requires a custom host environment (e.g., using a custom DI container like Autofac), you can implement a convention-based hook in your application.

    The tool will look for a class that follows one of these two naming conventions:

    1. A class named SwaggerHostFactory containing a public static IHost CreateHost() method.
    2. A class named SwaggerWebHostFactory containing a public static IWebHost CreateWebHost() method.
    public class SwaggerHostFactory
    {
        public static IHost CreateHost()
            => MyApplication.CreateHostBuilder([]).Build();
    }
  6. Assign Actions to Specific Swagger Documents

    master

    When using multiple documents, you must specify which actions belong to which document. You can do this via decoration or conventions.

    Decorate Individual Actions

    Use the [ApiExplorerSettings] attribute and set the GroupName property to the document name (case-sensitive).

    Assign Actions by Convention

    Implement IControllerModelConvention to group actions based on metadata like namespaces.

    Customize the Selection Process

    Use DocInclusionPredicate to define custom logic for including an ApiDescription in a document. This is useful when using external versioning attributes (like Microsoft.AspNetCore.Mvc.Versioning).

    // Decorate action
    [HttpPost]
    [ApiExplorerSettings(GroupName = "v2")]
    public void PostLine([FromBody] ProductLine product) { ... }
    
    // Custom inclusion predicate
    options.DocInclusionPredicate((docName, apiDesc) =>
    {
        if (!apiDesc.TryGetMethodInfo(out MethodInfo methodInfo))
        {
            return false;
        }
    
        var versions = methodInfo.DeclaringType?
            .GetCustomAttributes(true)
            .OfType<ApiVersionAttribute>()
            .SelectMany(attribute => attribute.Versions) ?? [];
    
        return versions.Any(version => $"v{version}" == docName);
    });
  7. Customize Swagger UI using a custom index.html

    master

    For advanced customization, you can provide your own index.html file. This requires adding the file as an EmbeddedResource in your project file and using IndexStream to provide the stream.

    // In C#
    app.UseSwaggerUI(options =>
    {
        options.IndexStream = () => typeof(Program).Assembly
            .GetManifestResourceStream("CustomUIIndex.Swagger.index.html");
    });
    <!-- In .csproj -->
    <Project>
      <ItemGroup>
        <EmbeddedResource Include="CustomUIIndex.Swagger.index.html" />
      </ItemGroup>
    </Project>
  8. List explicit operation responses

    master

    By default, Swashbuckle generates a 200 OK response. If your method returns a specific object, the schema for that object is automatically included.

    To specify different status codes, additional responses, or to describe responses when returning IActionResult, use the ASP.NET Core [ProducesResponseType] attribute.

    [HttpPost("product/{id}")]
    [ProducesResponseType(typeof(Product), 200)]
    [ProducesResponseType(typeof(IDictionary<string, string>), 400)]
    [ProducesResponseType(500)]
    public IActionResult GetProductInfoById(int id)
    {
        return Ok();
    }
  9. Customize Redoc using a custom index.html

    master

    For advanced customization, you can provide your own index.html file. This requires adding the file as an EmbeddedResource in your project and providing a delegate to options.IndexStream that returns the manifest resource stream.

    app.UseReDoc(options =>
    {
        options.IndexStream = () => typeof(Program).Assembly
            .GetManifestResourceStream("CustomIndex.ReDoc.index.html"); // Requires file to be added as an embedded resource
    });
    <Project>
      <ItemGroup>
        <EmbeddedResource Include="CustomIndex.ReDoc.index.html" />
      </ItemGroup>
    </Project>