Skip to content

Proposal: OpenApiOptions with Synchronous Transformer Overloads #60943

Open
@xC0dex

Description

@xC0dex

Background and Motivation

Since the release of .NET 9 and the new Microsoft.AspNetCore.OpenApi document generator, I have written and seen numerous transformers for OpenApiOperation and OpenApiDocument. In most instances, the implementation of these transformers has been synchronous, requiring the return of Task.CompletedTask. I believe it would enhance the developer experience if the package provided an Action<> overload for each transformer, eliminating the need to return a completed task for synchronous scenarios.

Proposed API

namespace Microsoft.AspNetCore.OpenApi;

public sealed class OpenApiOptions
{
+   public OpenApiOptions AddDocumentTransformer(Action<OpenApiDocument, OpenApiDocumentTransformerContext> transformer);

+   public OpenApiOptions AddOperationTransformer(Action<OpenApiOperation, OpenApiOperationTransformerContext> transformer);

+   public OpenApiOptions AddSchemaTransformer(Action<OpenApiSchema, OpenApiSchemaTransformerContext> transformer)
}

Usage Examples

Before:

options.AddDocumentTransformer((document, context, _) =>
{
    var descriptionProvider = context.ApplicationServices.GetRequiredService<IApiVersionDescriptionProvider>();
    var versionDescription = descriptionProvider.ApiVersionDescriptions.FirstOrDefault(x => x.GroupName == version);
    document.Info.Version = versionDescription?.ApiVersion.ToString();
    return Task.CompletedTask;
});

After:

options.AddDocumentTransformer((document, context) =>
{
    var descriptionProvider = context.ApplicationServices.GetRequiredService<IApiVersionDescriptionProvider>();
    var versionDescription = descriptionProvider.ApiVersionDescriptions.FirstOrDefault(x => x.GroupName == version);
    document.Info.Version = versionDescription?.ApiVersion.ToString();
});

Alternative Designs

There are not many alternative designs to consider. One alternative could be to leave everything as it is.

Risks

The only potential risk is that there could be a conflict if developers have already created custom overloads or extensions.

Metadata

Metadata

Assignees

No one assigned

    Labels

    api-suggestionEarly API idea and discussion, it is NOT ready for implementationarea-mvcIncludes: MVC, Actions and Controllers, Localization, CORS, most templatesfeature-openapi

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions