aspnetcore: IOpenApiDocumentTransformer cannot modify components.Schemas since it's null

Is there an existing issue for this?

  • I have searched the existing issues

Describe the bug

When running IOpenApiDocumentTransformer, it would be logical to have the ability to modify the OpenApiDocument.Components.Schemas to make any adjustments. The OpenApiDocument.Components is null.

https://github.com/dotnet/aspnetcore/blob/049814ca468cad1ea1e29412e0aa3eea182a63c1/src/OpenApi/src/Services/OpenApiDocumentService.cs#L100-L106

The await _schemaReferenceTransformer.TransformAsync(document, documentTransformerContext, cancellationToken) populates the Components.Schemas, but that happens after the document transformers are run.

Expected Behavior

It should be possible to modify Components.Schemas in the IOpenApiDocumentTransformer

Steps To Reproduce

No response

Exceptions (if any)

No response

.NET Version

.NET 9 RC2

Anything else?

No response

About this issue

  • Original URL
  • State: closed
  • Created 2 years ago
  • Reactions: 2
  • Comments: 15 (5 by maintainers)

Most upvoted comments

How does this new api allow us to enumerate all the existing schemas in the document? Some things can be done in a schema/operation transformer, but some things are easier to do when you have access to the totality. This might be an edge case, but when you have something called an IOpenApiDocumentTransformer you kinda expect to have access to the whole document.

I think I commented somewhere else, but I came up with this way after understanding that the annotation "x-schema-id is controls the naming:

public static OpenApiOptions ApplySchemaNameTransforms(this OpenApiOptions options, Func<Type, string> transformer)
{
    options.AddSchemaTransformer((schema, context, ct) =>
    {
        const string SchemaId = "x-schema-id";

        if (schema.Annotations?.TryGetValue(SchemaId, out var referenceIdObject) == true
             && referenceIdObject is string newSchemaId)
        {
            var clrType = context.JsonTypeInfo.Type;
            newSchemaId = transformer(clrType);
            schema.Annotations[SchemaId] = newSchemaId;
        }

        return Task.CompletedTask;
    });

    return options;
}

Polymorphic classes:

Yes, changing name doesn’t work for polymorphic classes since that is dealt by its own private set of transformer methods that are run by default after the transformers have run.

Would be nice if those could become regular transformers, and that there would be transformers that allowed for inheritance, similar to what NSwag and Swashbuckle does by default.

On the IOpenApiDocumentTransformer:

Transformers should be seen as middleware, if that makes sense. But the final composition stage happens after all the transformer have run. That is when similar schemas are being merged and placed in Schemas in OpenApiDocument.

Because of what is mention above, it makes sense that at the transformer stage the “Components.Schemas” are not populated. But still confusing that the property is there if you, as a developer, don’t understand this. Because you might expect that a IOpenApiDocumentTransformer has the complete document, which it does not have.

Question:

Should there be a way to hook into when a document has been fully composed? That would give you ability to do finishing touches. Even if risky.

It’s a huge oversight that the IOpenApiDocumentTransformer isn’t the last stop in document generation. What use is it if we don’t have access to the complete specification?

I have problems with this too. I want to remove some specific schemas that are generated by default. I can’t use a schematransformer to remove a schema, and i can’t edit the nulled list of schemas in the documenttransformer.

I think I commented somewhere else, but I came up with this way after understanding that the annotation "x-schema-id is controls the naming:

    public static OpenApiOptions ApplySchemaNameTransforms(this OpenApiOptions options, Func<Type, string> transformer)
    {
        options.AddSchemaTransformer((schema, context, ct) =>
        {
            const string SchemaId = "x-schema-id";

            if (schema.Annotations?.TryGetValue(SchemaId, out var referenceIdObject) == true
                 && referenceIdObject is string newSchemaId)
            {
                var clrType = context.JsonTypeInfo.Type;
                newSchemaId = transformer(clrType);
                schema.Annotations[SchemaId] = newSchemaId;
            }

            return Task.CompletedTask;
        });

        return options;
    }

Polymorphic classes:

Yes, changing name doesn’t work for polymorphic classes since that is dealt by its own private set of transformer methods that are run by default after the transformers have run.

Would be nice if those could become regular transformers, and that there would be transformers that allowed for inheritance, similar to what NSwag and Swashbuckle does by default.


On the IOpenApiDocumentTransformer:

Transformers should be seen as middleware, if that makes sense. But the final composition stage happens after all the transformer have run. That is when similar schemas are being merged and placed in Schemas in OpenApiDocument.

Because of what is mention above, it makes sense that at the transformer stage the “Components.Schemas” are not populated. But still confusing that the property is there if you, as a developer, don’t understand this. Because you might expect that a IOpenApiDocumentTransformer has the complete document, which it does not have.

Question:

Should there be a way to hook into when a document has been fully composed? That would give you ability to do finishing touches. Even if risky.

You can use this middleware to modify the response on the way out. In this example I’m removing well-known types that I don’t want in the response. They key part is loading it into the OpenApiStringReader which then allows you to modify any part of the document;

public static void UseCustomSwagger(this IApplicationBuilder app)
{
    string[] excludedSchemaTypes = [
    "Microsoft.AspNetCore.Mvc.ValidationProblemDetails",
    "Microsoft.AspNetCore.Mvc.ProblemDetails",
    "Microsoft.AspNetCore.Http.HttpValidationProblemDetails"];

    app.Use(async (context, next) =>
        {
            if (context.Request.Path == "/swagger/v1/swagger.json")
            {
                var originalBodyStream = context.Response.Body;
                using (var memoryStream = new MemoryStream())
                {
                    // Replace the response body stream with the memory stream
                    context.Response.Body = memoryStream;

                    await next.Invoke(); // Call the next middleware

                    // Reset the position to read from the beginning
                    memoryStream.Seek(0, SeekOrigin.Begin);
                    string responseBody = await new StreamReader(memoryStream).ReadToEndAsync();

                    var reader = new OpenApiStringReader();
                    var openApiDocument = reader.Read(responseBody, out var diagnostic);

                    var remove = openApiDocument.Components.Schemas.Where(s => excludedSchemaTypes.Contains(s.Value.Type));
                    foreach (var schema in remove)
                    {
                        openApiDocument.Components.Schemas.Remove(schema.Key);
                    }


                    using var stringWriter = new StringWriter();
                    var jsonWriter = new OpenApiJsonWriter(stringWriter);
                    openApiDocument.SerializeAsV3(jsonWriter);
                    jsonWriter.Flush();
                    var modifiedResponseBody = stringWriter.ToString();


                    byte[] modifiedBytes = Encoding.UTF8.GetBytes(modifiedResponseBody);

                    // Set the response content length if needed
                    context.Response.ContentLength = modifiedBytes.Length;
                    await originalBodyStream.WriteAsync(modifiedBytes);

                    return;
                }

            }

            await next();


        });
}

Unfortunately that code sample isn’t working for me - document.Components is always null in the document transformer.

To clarify, the code sample only works for .NET 10 because we take a dependency on some API changes in Microsoft.OpenApi v2. This isn’t feasible in .NET 9 and we likely won’t be making any retroactive changes to support it.

How does this new api allow us to enumerate all the existing schemas in the document? Some things can be done in a schema/operation transformer, but some things are easier to do when you have access to the totality. This might be an edge case, but when you have something called an IOpenApiDocumentTransformer you kinda expect to have access to the whole document.

In the new model, you do have access to the all the schemas in the document since they are inserted into the document as they are constructed instead of via a document transformer as the final step (as in the current model).

The following code:

using System.Diagnostics;

var builder = WebApplication.CreateBuilder(args);

builder.Services.AddOpenApi(options =>
{
    options.AddDocumentTransformer((document, context, ct) =>
    {
        Debug.Assert(document.Components != null, "Components should not be null");
        Debug.Assert(document.Components.Schemas != null, "Schemas should not be null");
        foreach (var schema in document.Components.Schemas)
        {
            Console.WriteLine(schema.Key);
        }
        return Task.CompletedTask;
    });
});

var app = builder.Build();

if (app.Environment.IsDevelopment())
{
    app.MapOpenApi();
}

app.MapPost("/weather", (WeatherForecast forecast) => { });
app.MapPost("/todo", (Todo todo) => { });
app.MapPost("/user", (User user) => { });

app.Run();

record WeatherForecast(DateOnly Date, int TemperatureC, string? Summary);
record Todo(int Id, string Title, bool Completed);
record User(int Id, string Name, string Email);

will write the following to the console:

WeatherForecast
Todo
User

Unfortunately that code sample isn’t working for me - document.Components is always null in the document transformer.

In my case I have an OData endpoint which causes the Open API document to include a bunch of objects not really relevant to the API end users:

Image

Using Swashbuckle.AspNetCore.SwaggerGen I am able to remove schemas from the final open API document using the IDocumentFilter interface and the document.Components.Schemas.Remove() method in code similar to this:

Image

I am not seeing any way to remove schemas in the new Microsoft.AspNetCore.OpenApi IOpenApiDocumentTransformer since the Components object is always null on the document:

Image

Is there any way to remove or update schemas similar to how we currently can using the SwaggerGen package?

I’m finding it quite frustrating trying to extend the default spec for this same reason mentioned here. I want to have an API endpoint that allows for partial model fields to be provided, which would be quite easy in other languages/frameworks. I’ve also found that the generated doc does not respect the configuration specified by WithOpenApi on a RouteHandlerBuilder. I feel like any IOpenApiDocumentTransformer implementations we provide should be the last stop after all other generation has occurred so that we can customize to our exact needs.

@dnv-kimbell This is expected behavior. If you are trying to make schema-level customizations, the IOpenApiSchemaTransformer API is the one that you want to use.

What are you trying to do?