Support options for setting callback used to generated reference IDs in OpenAPI #56305
Description
Background and Motivation
The OpenAPI implementation generates reference IDs for schemas that are duplicated across the OpenAPI document. By default, a unique identifier is generated for the schema using a combination of the schema itself and the type associated with the schema. At times, it might be necessary for users to override our default behavior with their own reference ID generation function.
Proposed API
namespace Microsoft.AspNetCore.OpenApi;
public sealed class OpenApiOptions
{
+ public Func<JsonTypeInfo, string?> CreateSchemaReferenceId { get; set; }
}
Usage Examples
var builder = WebApplication.CreateBuilder();
builder.Services.AddOpenApi(options =>
{
CreateSchemaReferenceId = (jsonTypeInfo) => $"My{jsonTypeInfo.Type.Name}",
});
builder.Services.AddOpenApi(options =>
{
// Returning null means that all schemas will be inlined, can also be used to
// conditional inline a schema
CreateSchemaReferenceId = (jsonTypeInfo) => null,
});
var app = builder.Build();
app.MapOpenApi();
app.MapGet("/", () => "Hello world!");
app.Run();
Alternative Designs
Instead of specifying custom schema IDs via a callback, we could support a custom attribute on types that would allow users to set reference IDs for the types they care about. For example:
[SchemaReferenceId("some-name-here")]
public class Todo { }
Risks
Exposing an option for customizing the way reference IDs are created adds additional burden onto the user to ensure that the callback they provide will generate unique and accurate reference IDs for all the types that are used in their application.