RA.Utilities.OpenApi 10.0.6

Prefix Reserved
dotnet add package RA.Utilities.OpenApi --version 10.0.6
                    
NuGet\Install-Package RA.Utilities.OpenApi -Version 10.0.6
                    
This command is intended to be used within the Package Manager Console in Visual Studio, as it uses the NuGet module's version of Install-Package.
<PackageReference Include="RA.Utilities.OpenApi" Version="10.0.6" />
                    
For projects that support PackageReference, copy this XML node into the project file to reference the package.
<PackageVersion Include="RA.Utilities.OpenApi" Version="10.0.6" />
                    
Directory.Packages.props
<PackageReference Include="RA.Utilities.OpenApi" />
                    
Project file
For projects that support Central Package Management (CPM), copy this XML node into the solution Directory.Packages.props file to version the package.
paket add RA.Utilities.OpenApi --version 10.0.6
                    
#r "nuget: RA.Utilities.OpenApi, 10.0.6"
                    
#r directive can be used in F# Interactive and Polyglot Notebooks. Copy this into the interactive tool or source code of the script to reference the package.
#:package RA.Utilities.OpenApi@10.0.6
                    
#:package directive can be used in C# file-based apps starting in .NET 10 preview 4. Copy this into a .cs file before any lines of code to reference the package.
#addin nuget:?package=RA.Utilities.OpenApi&version=10.0.6
                    
Install as a Cake Addin
#tool nuget:?package=RA.Utilities.OpenApi&version=10.0.6
                    
Install as a Cake Tool

RA.Utilities.OpenApi

NuGet version Codecov NuGet Downloads Documentation GitHub license

A utility library to enhance and customize OpenAPI (Swagger) documentation in ASP.NET Core applications.

This package provides a collection of IOpenApiDocumentTransformer implementations to automate common modifications to your generated OpenAPI specification. Instead of manually annotating every endpoint with attributes for common headers or security schemes, you can apply these transformations globally.

The primary goals are to:

  • Reduce Boilerplate: Automatically add common parameters (like correlation IDs) to all API operations.
  • Enforce Consistency: Ensure that all endpoints consistently document required headers and responses.
  • Simplify Configuration: Keep your endpoint definitions clean by centralizing OpenAPI modifications.

📚 Table of Contents

  • Getting started
  • Dependencies
  • Document Transformers
    • DocumentInfoTransformer
    • BearerSecuritySchemeTransformer
    • HeadersParameterTransformer
    • BearerSecurityDocumentTransformer
  • Operation Transformers
    • DefaultResponsesOperationTransformer
  • Schema Filters (as Document Transformers)
    • PolymorphismDocumentTransformer
  • Utilities
    • OpenApiOperationUtilities
  • Configuration
    • OpenApiInfoSettings
    • HeadersParameterSettings
    • Example appsettings.json
  • Usage
  • Contributing

Getting started

Install the package via the .NET CLI:

dotnet add package RA.Utilities.OpenApi

Or through the NuGet Package Manager in Visual Studio.


Default Transformers

This package includes a set of default transformers that can be registered with a single extension method, AddDefaultsDocumentTransformer().

DocumentInfoTransformer

This transformer populates the top-level information of your OpenAPI document (like title, version, description, and contact info) directly from your appsettings.json configuration.

What it does:

  1. Reads from Configuration: It uses OpenApiInfoSettings to bind to a configuration section (e.g., OpenApi:Info).
  2. Populates OpenApiInfo: It sets the Title, Version, Description, Contact, and License fields in the generated document.
  3. Simplifies Customization: Allows you to update your API's documentation details without changing any code.

BearerSecuritySchemeTransformer

This transformer automatically adds a "Bearer" security scheme to your OpenAPI document if it detects that JWT Bearer authentication is registered in your application. This enables the "Authorize" button in the Swagger UI, allowing users to test protected endpoints.

What it does:

  1. Detects JWT Authentication: It checks if an authentication scheme named Bearer or BearerToken is present.
  2. Adds Security Scheme: If detected, it adds the standard JWT Bearer security definition to the document's components.
  3. Reduces Boilerplate: Eliminates the need to manually configure AddSecurityDefinition and AddSecurityRequirement in SwaggerGenOptions for this common scenario.

HeadersParameterTransformer

This document transformer automatically adds common correlation and tracing headers to every operation in your OpenAPI document. This is useful for microservices and distributed systems where tracking requests is essential.

What it does:

  1. Adds Request Headers: It adds headers like x-request-id as parameters to all API requests. This documents the need for clients to provide a unique identifier for each call.
  2. Adds Response Headers: It adds headers like x-request-id and trace-id to all possible responses for every operation. This informs clients that they can expect these headers back for logging and debugging.

Both the request and response headers are configurable via HeadersParameterSettings.

ResponsesDocumentTransformer

This transformer automatically adds standardized OpenAPI responses for common HTTP status codes like 400, 404, 409, and 500. It uses the response models from RA.Utilities.Api.Results to generate the schema for these error responses.

What it does:

  1. Standardizes Error Responses: Ensures that your OpenAPI documentation accurately reflects the structured error responses (BadRequestResponse, NotFoundResponse, ConflictResponse, ErrorResponse) that your API produces.
  2. Reduces Annotations: Eliminates the need to manually add [ProducesResponseType] attributes for these common errors on every single endpoint.

Operation Transformers

DefaultResponsesOperationTransformer

This operation transformer automatically adds standardized OpenAPI responses for common HTTP status codes for 500. It uses the response models from RA.Utilities.Api.Results to generate the schema for these error responses.

This transformer is an IOpenApiOperationTransformer, meaning it applies to each API operation individually. It is a more targeted alternative to the ResponsesDocumentTransformer.

What it does:

  1. Standardizes Error Responses: Ensures that your OpenAPI documentation accurately reflects the structured error responses (ErrorResponse) that your API produces.
  2. Reduces Annotations: Eliminates the need to manually add [ProducesResponseType] attributes for these common errors on every single endpoint.
  3. Operation-Level Granularity: As an IOpenApiOperationTransformer, it integrates seamlessly with Swashbuckle's operation-level processing pipeline.

Schema Filters (as Document Transformers)

PolymorphismDocumentTransformer

This document transformer enhances the OpenAPI documentation for APIs that use polymorphic types (i.e., base classes with multiple derived classes). It correctly represents the inheritance structure in the generated schema using the oneOf and discriminator keywords, making it understandable for clients and code generation tools.

Unlike a Swashbuckle ISchemaFilter, this is an IOpenApiDocumentTransformer that works with ASP.NET Core's native OpenAPI generation (Microsoft.AspNetCore.OpenApi).

What it does:

  1. Finds the Base Schema: It locates the schema for a specified base type in the OpenAPI document.
  2. Generates Derived Schemas: It ensures that schemas for all specified derived types are present in the document, creating them if necessary.
  3. Adds oneOf and discriminator: It modifies the base schema to use the oneOf keyword, listing all derived types, and adds a discriminator object to tell clients how to determine the correct type based on a property (e.g., "type").
  4. Enables Code Generation: Fixes issues with client-side code generators like NSwag or AutoRest where polymorphic types would otherwise be ignored or misinterpreted.

To apply this transformer, you need to instantiate it with the required parameters and register it in Program.cs.

// Program.cs
builder.Services.AddOpenApiDocumentTransformer(new PolymorphismDocumentTransformer(
    polymorphismPropertyName: "Error", // The name of the base schema
    typesToInclude: new() // A dictionary of derived types
    {
        { "NotFound", typeof(NotFoundResponse) },
        { "Conflict", typeof(ConflictResponse) },
    }
));

Configuration

The transformers are configured via appsettings.json. Below are the details for the available settings classes.

OpenApiInfoSettings

Used by DocumentInfoTransformer to populate the document's info object.

appsettings.json Section: OpenApi:Info

Property Type Description
Title string The title of the API.
Version string The version of the API.
Description string A short description of the API.
TermsOfService string (URI) A URL to the Terms of Service for the API.
Contact OpenApiContactSettings (object) The contact information for the exposed API. See details below.
License OpenApiLicenseSettings (object) The license information for the exposed API. See details below.
OpenApiContactSettings
Property Type Description
Name string The identifying name of the contact person/organization.
Email string The email address of the contact person/organization.
Url string (URI) The URL pointing to the contact information.
OpenApiLicenseSettings
Property Type Description
Name string The license name used for the API.
Url string (URI) A URL to the license used for the API.

HeadersParameterSettings

Used by HeadersParameterTransformer to add common headers to requests and responses.

appsettings.json Section: OpenApiHeaders

Property Type Description
RequestHeaders List<[HeaderDefinition](#eaderdefinition)> A list of header definitions to add to all API requests.
ResponseHeaders List<[HeaderDefinition](#eaderdefinition)> A list of header definitions to add to all API responses.
HeaderDefinition

Represents a single header to be added to the OpenAPI specification.

Property Type Default Description
Name string "" The name of the header (e.g., "x-request-id").
Description string "" A description of the header's purpose.
Required bool true Specifies if the header is required.
Type JsonSchemaType String The schema type for the header value (e.g., "String", "Integer").
Format string "uuid" The format of the header value (e.g., "uuid", "date-time").
Value object null An example value for the header.

Example appsettings.json

{
  "OpenApiInfoSettings": {
    "Info": {
      "Title": "My Awesome API",
      "Version": "v1.0.0",
      "Summary": "A brief and catchy summary of the API.",
      "Description": "This is a more detailed description of the API. It can include **Markdown** for rich text formatting, explaining what the API does, its main features, and how to get started.",
      "TermsOfService": "https://example.com/terms",
      "Contact": {
        "Name": "API Support Team",
        "Url": "https://example.com/support",
        "Email": "support@example.com"
      },
      "License": {
        "Name": "MIT License",
        "Url": "https://opensource.org/licenses/MIT"
      }
    }
  },
  "OpenApiHeaders": {
    "RequestHeaders": [
      {
        "Name": "x-request-id",
        "Description": "A unique identifier for the API call, used for tracing.",
        "Required": true
      }
    ]
  }
}

🔗 Dependencies

Usage

The easiest way to get started is by using the provided extension methods to register the various transformers and filters.

// Program.cs

using Microsoft.OpenApi.Models;
using RA.Utilities.OpenApi.DocumentTransformers;
using RA.Utilities.OpenApi.Extensions;
using RA.Utilities.OpenApi.OperationTransformers;
using RA.Utilities.OpenApi.SchemaFilters;
using RA.Utilities.OpenApi.Settings;

var builder = WebApplication.CreateBuilder(args);

// Add services to the container.
builder.Services.AddEndpointsApiExplorer();

// 1. (Optional) Configure settings from appsettings.json for the transformers.
builder.Services.Configure<OpenApiInfoSettings>(builder.Configuration.GetSection(OpenApiInfoSettings.AppSettingsKey));
builder.Services.Configure<HeadersParameterSettings>(builder.Configuration.GetSection(HeadersParameterSettings.AppSettingsKey));

// 2. Add OpenAPI services.
// Use AddSwaggerGen() for controller-based APIs or more advanced scenarios.
builder.Services.AddOpenApi()
    .AddDefaultsDocumentTransformer();

// 3. Register additional document transformers individually.
builder.Services.AddOpenApiDocumentTransformer<BearerSecurityDocumentTransformer>();

// 4. Register operation transformers for more granular control.
builder.Services.AddOpenApiOperationTransformer<DefaultResponsesOperationTransformer>();

// 5. If using Swashbuckle (AddSwaggerGen), you can add schema filters.
// This is shown for completeness. AddSwaggerGen() is needed for this to work.
builder.Services.AddSwaggerGen(options =>
{
    options.SchemaFilter<PolymorphismDocumentTransformer>();
});

var app = builder.Build();

// Configure the HTTP request pipeline.
if (app.Environment.IsDevelopment())
{
    app.UseSwagger();
    app.UseSwaggerUI();
}

// 6. Map the OpenAPI document endpoints.
app.MapOpenApi();

app.MapGet("/weatherforecast", () => "Hello World!")
   .WithName("GetWeatherForecast")
   .WithOpenApi();

app.Run();

With this transformer enabled, your Swagger UI will now show predefined response schemas for 400, 404, 409, and 500 status codes on all endpoints, matching the structure of your RA.Utilities.Api.Results models.

Utilities

OpenApiOperationUtilities

The OpenApiOperationUtilities class is a static helper that provides methods for programmatically adding examples to requests and responses within an OpenApiOperation. This is particularly useful when creating custom IOperationFilter implementations where you need to add dynamic or complex examples to specific endpoints.

Key Functions:
  • AddRequestExample(...): Attaches a named example to the request body of an operation for a given media type (defaults to application/json).
  • AddRequestExamples(...): Attaches multiple named examples to the request body of an operation.
  • AddResponseExample(...): Attaches a named example to a specific HTTP status code response for an operation. This is great for showing what a successful response looks like or detailing the structure of a specific error.
  • AddGeneralErrorResponse(...): A specialized shortcut method that adds a pre-defined example for a 500 Internal Server Error.
  • AddResponseExamples(...): Attaches multiple named examples to a specific HTTP status code response.
Example Usage in an IOperationFilter

Additional documentation

For more information on how this package fits into the larger RA.Utilities ecosystem, please see the main repository documentation.

Contributing

Contributions are welcome! If you have a suggestion or find a bug, please open an issue to discuss it.

Pull Request Process

  1. Fork the Repository: Start by forking the RA.Utilities repository.
  2. Create a Branch: Create a new branch for your feature or bug fix from the main branch. Please use a descriptive name (e.g., feature/add-security-transformer or fix/readme-typo).
  3. Make Your Changes: Write your code, ensuring it adheres to the existing coding style. Add or update XML documentation for any new public APIs.
  4. Update README: If you are adding new functionality, please update the README.md file accordingly.
  5. Submit a Pull Request: Push your branch to your fork and open a pull request to the main branch of the original repository. Provide a clear description of the changes you have made.

Coding Standards

  • Follow the existing coding style and conventions used in the project.
  • Ensure all public members are documented with clear XML comments.
  • Keep changes focused. A pull request should address a single feature or bug.

Thank you for contributing!

Product Compatible and additional computed target framework versions.
.NET net10.0 is compatible.  net10.0-android was computed.  net10.0-browser was computed.  net10.0-ios was computed.  net10.0-maccatalyst was computed.  net10.0-macos was computed.  net10.0-tvos was computed.  net10.0-windows was computed. 
Compatible target framework(s)
Included target framework(s) (in package)
Learn more about Target Frameworks and .NET Standard.

NuGet packages

This package is not used by any NuGet packages.

GitHub repositories

This package is not used by any popular GitHub repositories.

Version Downloads Last Updated
10.0.6 87 1/7/2026
10.0.5 175 12/23/2025
10.0.4 262 12/18/2025
10.0.3 279 12/17/2025
10.0.2 266 12/17/2025
10.0.1 121 12/12/2025
10.0.0 193 11/24/2025
10.0.0-rc.2 164 10/30/2025