RA.Utilities.OpenApi
10.3.1
Prefix Reserved
dotnet add package RA.Utilities.OpenApi --version 10.3.1
NuGet\Install-Package RA.Utilities.OpenApi -Version 10.3.1
<PackageReference Include="RA.Utilities.OpenApi" Version="10.3.1" />
<PackageVersion Include="RA.Utilities.OpenApi" Version="10.3.1" />
<PackageReference Include="RA.Utilities.OpenApi" />
paket add RA.Utilities.OpenApi --version 10.3.1
#r "nuget: RA.Utilities.OpenApi, 10.3.1"
#:package RA.Utilities.OpenApi@10.3.1
#addin nuget:?package=RA.Utilities.OpenApi&version=10.3.1
#tool nuget:?package=RA.Utilities.OpenApi&version=10.3.1
RA.Utilities.OpenApi
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
- Operation Transformers
- Schema Transformers
- Utilities
- Configuration
- 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.
Document Transformers
This package includes a set of document 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:
- Reads from Configuration: It uses
OpenApiInfoSettingsto bind to a configuration section (e.g.,OpenApiInfoSettings). - Populates
OpenApiInfo: It sets theTitle,Version,Description,Summary,TermsOfService,Contact, andLicensefields in the generated document (theSummaryfield is populated since v10.1.1). - Simplifies Customization: Allows you to update your API's documentation details without changing any code.
BearerSecurityDocumentTransformer
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:
- Detects JWT Authentication: It checks if an authentication scheme named
BearerorBearerTokenis present. - Adds Security Scheme: If detected, it adds the standard JWT Bearer security definition to the document's components.
- Reduces Boilerplate: Eliminates the need to manually configure
AddSecurityDefinitionandAddSecurityRequirementinSwaggerGenOptionsfor 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:
- Adds Request Headers: It adds headers like
x-request-idas parameters to all API requests. This documents the need for clients to provide a unique identifier for each call. - Adds Response Headers: It adds headers like
x-request-idandtrace-idto 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.
HealthChecksDocumentTransformer
This document transformer adds your service's health check endpoints to the OpenAPI document. Endpoints mapped with MapHealthChecks carry no API metadata, so the OpenAPI generator never includes them; this transformer documents them explicitly.
What it does:
- Documents
GET /health: The readiness endpoint that returns the aggregate health status of the service together with the result of each registered health check, asapplication/json(200/503responses described with theHealthCheckReportschema). - Documents
GET /alive: The liveness endpoint that returns the service state as plain text (Healthy,Degraded, orUnhealthy), based on the health checks tagged withlive(200/503responses astext/plain). - Adds component schemas:
HealthCheckReport(aggregatestatus,totalDuration, and per-checkentries) andHealthCheckEntry(data,description,duration,exception,status,tags). - Adds the
Healthtag and keeps the operations anonymous — the transformer runs after the Bearer security transformer, so no security scheme is applied and the endpoints stay reachable without authentication.
It is registered automatically by AddDefaultsDocumentTransformer().
⚠️ Known issue (v10.1.0, still present in v10.3.1): The standalone
AddHealthChecksDocumentTransformer(IDictionary<string, string> tags)extension method currently registersHeadersParameterTransformerinstead ofHealthChecksDocumentTransformer, and thetagsargument is ignored. UseAddDefaultsDocumentTransformer()until this is corrected.
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.Response (namespace RA.Utilities.Api.Response) 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:
- Standardizes Error Responses: Ensures that your OpenAPI documentation accurately reflects the structured error responses (
ErrorResponse) that your API produces. - Reduces Annotations: Eliminates the need to manually add
[ProducesResponseType]attributes for these common errors on every single endpoint. - Operation-Level Granularity: As an
IOpenApiOperationTransformer, it integrates seamlessly with ASP.NET Core's native operation-level processing pipeline.
Polymorphism (as a Document Transformer)
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:
- Finds the Base Schema: It locates the schema for a specified base type in the OpenAPI document.
- Generates Derived Schemas: It ensures that schemas for all specified derived types are present in the document, creating them if necessary.
- Adds
oneOfanddiscriminator: It modifies the base schema to use theoneOfkeyword, listing all derived types, and adds adiscriminatorobject to tell clients how to determine the correct type based on a property (e.g.,"type"). - 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, use the AddPolymorphismDocumentTransformer<T> extension method:
// Program.cs
builder.Services.AddOpenApi(options =>
{
options.AddPolymorphismDocumentTransformer<Animal>(new Dictionary<string, Type>
{
{ "Cat", typeof(Cat) },
{ "Dog", typeof(Dog) },
});
});
Schema Transformers
FluentValidationSchemaTransformer
This transformer enriches your OpenAPI schema by applying constraints from your FluentValidation validators. It inspects registered IValidator<T> implementations and adds corresponding constraints (required, length, pattern, range) to the generated schema properties.
Supported Rules:
NotNull/NotEmpty→ marks property as requiredLength/MinimumLength/MaximumLength→ setsminLength/maxLengthMatches→ setspatternGreaterThan/LessThan→ setsminimum/maximumwith exclusive flagsInclusiveBetween/ExclusiveBetween→ setsminimum/maximumrangeEmailAddress→ sets format toemailCreditCard→ sets format tocredit-card
builder.Services.AddOpenApi(options =>
{
options.AddFluentValidationRules();
});
ValueObjectSchemaTransformer
Documents the constraints enforced by the value objects from RA.Utilities.Core.ValueObjects directly in the generated schema. The OpenAPI generator cannot see the validation performed by a value object's constructor, so without this transformer Email, Currency, SSN, and IBAN appear as property-less objects.
| Value object | Documented schema |
|---|---|
Email |
string, format: email, pattern, minLength: 1, maxLength: 254 |
Currency |
string, pattern, minLength: 3, maxLength: 3 |
SSN |
string, pattern, minLength: 10, maxLength: 10 |
IBAN |
string, format: iban, pattern, minLength: 13, maxLength: 34 |
Money |
object description and example |
Each schema also receives a description and an example value. The transformer is idempotent and is registered automatically by AddDefaultsDocumentTransformer(). When registering transformers individually, add it explicitly:
builder.Services.AddOpenApi(options =>
{
options.AddValueObjectSchemaTransformer();
});
EnumXmlSchemaTransformer
Enhances enum definitions in the OpenAPI schema by reading XML documentation comments and appending a markdown table with value descriptions. Requires your project to generate an XML documentation file.
var xmlFile = $"{Assembly.GetExecutingAssembly().GetName().Name}.xml";
var xmlPath = Path.Combine(AppContext.BaseDirectory, xmlFile);
builder.Services.AddOpenApi(options =>
{
options.AddEnumXmlDescriptionTransformer(xmlPath);
});
TagOperationTransformer
Allows you to add or update descriptions for OpenAPI tags, which is useful for documenting controller groups without cluttering the code with attributes.
builder.Services.AddOpenApi(options =>
{
options.AddTagOperationTransformer(new Dictionary<string, string>
{
{ "Products", "Operations related to product management." },
{ "Orders", "Operations for processing customer orders." }
});
});
GroupTagsDocumentTransformer
Writes group-level documentation declared with WithGroupSummary() / WithGroupDescription() into the OpenAPI tags of a route group. Endpoint-level WithSummary() / WithDescription() metadata is left untouched, so the group text and the endpoint text never fight over the same field.
using RA.Utilities.OpenApi.Extensions;
var orders = app.MapGroup("/orders")
.WithTags("Orders")
.WithGroupSummary("Order management")
.WithGroupDescription("Create, update, and track customer orders.");
The composed description is **Summary** + a blank line + Description when both are set, or the summary/description alone when only one is set. Group text is written only to tags the endpoints actually carry, and an existing tag description is never overwritten. AddDefaultsDocumentTransformer() registers the transformer automatically.
⚠️ Known issue (v10.3.0): The standalone
AddGroupTagsDocumentTransformer(IDictionary<string, string> tags)method requires atagsargument but ignores it — group text comes from the route group's metadata. UseAddDefaultsDocumentTransformer()until this is corrected.
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: OpenApiInfoSettings
| Property | Type | Description |
|---|---|---|
| UiReferenceEndpoint | string |
The endpoint where the Scalar API reference UI is mapped. Defaults to "/". |
| Title | string |
The title of the API. |
| Summary | string |
A short summary of the API. Populated into the document since v10.1.1. |
| 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. |
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. |
| Identifier | string |
An SPDX license expression for the API. The identifier field is mutually exclusive of the url field. |
| 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](#headerdefinition)> |
A list of header definitions to add to all API requests. |
| ResponseHeaders | List<[HeaderDefinition](#headerdefinition)> |
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? |
null |
The format of the header value (e.g., "uuid", "date-time"). The default header definitions use "uuid". |
| Value | object? |
null |
An example value for the header. |
Example appsettings.json
{
"OpenApiInfoSettings": {
"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
FluentValidationMicrosoft.AspNetCore.OpenApiRA.Utilities.ApiRA.Utilities.Api.ResponseRA.Utilities.Core.ValueObjects
Usage
Recommended: Using Default Transformers
The easiest way to get started is by using the provided extension methods to register the various transformers and filters.
// Program.cs
using RA.Utilities.OpenApi.Extensions;
using RA.Utilities.OpenApi.Settings;
var builder = WebApplication.CreateBuilder(args);
// 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 and register the transformers.
builder.Services.AddOpenApi(options =>
{
// Default transformers (DocumentInfo, BearerSecurity, Headers, HealthChecks, GroupTags)
// and the value object schema definitions.
options.AddDefaultsDocumentTransformer();
// 3. Register operation transformers for more granular control.
options.AddDefaultResponsesOperationTransformer();
// 4. Register FluentValidation schema enrichment.
options.AddFluentValidationRules();
});
var app = builder.Build();
// 5. Map the OpenAPI document endpoint (e.g. /openapi/v1.json).
app.MapOpenApi();
// Optional: map an interactive API reference UI (e.g. Scalar) over the document.
app.MapGet("/weatherforecast", () => "Hello World!")
.WithName("GetWeatherForecast");
app.Run();
With these transformers enabled, your API reference UI will show predefined response schemas for common status codes and standardized request headers on all endpoints.
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 IOpenApiOperationTransformer 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 response examples, each with its own status code, to an operation.
Behavior (v10.3.1):
AddRequestExampleandAddResponseExamplecreate the media type'sExamplesdictionary when it is empty, so examples are added even when the operation had none.AddResponseExamplerequires the operation to already define the target status code with aContententry for the media type — otherwise it throwsNullReferenceException(it returns silently when the status code itself is absent).AddRequestExampleskips silently when the request body or media type is absent.
Limitation:
AddResponseExamplescurrently ignores the per-itemOpenApiResponseExample.MediaTypeand always usesapplication/json. UseAddResponseExampledirectly for other media types.
Example Usage in a Custom Operation Transformer
// Add a single request example
OpenApiOperationUtilities.AddRequestExample(operation, "CreateProduct",
new OpenApiExample
{
Summary = "A new product",
Value = JsonSerializer.SerializeToNode(new { Name = "Widget", Price = 9.99m })
});
// Add a response example for a specific status code
OpenApiOperationUtilities.AddResponseExample(operation, StatusCodes.Status200OK,
"ProductResponse",
new OpenApiExample
{
Summary = "Product created",
Value = JsonSerializer.SerializeToNode(new { Id = 1, Name = "Widget", Price = 9.99m })
});
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
- Fork the Repository: Start by forking the RA.Utilities repository.
- Create a Branch: Create a new branch for your feature or bug fix from the
mainbranch. Please use a descriptive name (e.g.,feature/add-security-transformerorfix/readme-typo). - Make Your Changes: Write your code, ensuring it adheres to the existing coding style. Add or update XML documentation for any new public APIs.
- Update README: If you are adding new functionality, please update the
README.mdfile accordingly. - Submit a Pull Request: Push your branch to your fork and open a pull request to the
mainbranch 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 | Versions 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. |
-
net10.0
- FluentValidation (>= 12.2.0)
- Microsoft.AspNetCore.OpenApi (>= 10.0.14)
- Microsoft.OpenApi (>= 2.13.0)
- RA.Utilities.Api.Response (>= 10.2.0)
- RA.Utilities.Core.ValueObjects (>= 10.2.0)
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.3.1 | 117 | 11/1/2026 |
| 10.3.0 | 107 | 10/28/2026 |
| 10.2.1 | 104 | 10/19/2026 |
| 10.2.0 | 116 | 10/18/2026 |
| 10.1.0 | 108 | 10/11/2026 |
| 10.0.11 | 127 | 9/28/2026 |
| 10.0.8 | 167 | 4/25/2026 |
| 10.0.7 | 148 | 3/24/2026 |
| 10.0.6 | 177 | 1/7/2026 |
| 10.0.5 | 239 | 12/23/2025 |
| 10.0.4 | 329 | 12/18/2025 |
| 10.0.3 | 354 | 12/17/2025 |
| 10.0.2 | 333 | 12/17/2025 |
| 10.0.1 | 195 | 12/12/2025 |
| 10.0.0 | 265 | 11/24/2025 |
| 10.0.0-rc.2 | 239 | 10/30/2025 |