|
| 1 | +### Support for generating OpenApiSchemas in transformers |
| 2 | +<!-- https://github.com/dotnet/aspnetcore/pull/61050 --> |
| 3 | + |
| 4 | +Developers can now generate a schema for a C# type, using the same logic as ASP.NET Core OpenAPI document generation, |
| 5 | +and add it to the OpenAPI document. The schema can then be referenced from elsewhere in the OpenAPI document. |
| 6 | + |
| 7 | +The context passed to document, operation, and schema transformers now has a `GetOrCreateSchemaAsync` method that can be used to generate a schema for a type. |
| 8 | +This method also has an optional `ApiParameterDescription` parameter to specify additional metadata for the generated schema. |
| 9 | + |
| 10 | +To support adding the schema to the OpenAPI document, a `Document` property has been added to the Operation and Schema transformer contexts. This allows any transformer to add a schema to the OpenAPI document using the document's `AddComponent` method. |
| 11 | + |
| 12 | +#### Example |
| 13 | + |
| 14 | +To use this feature in an document, operation, or schema transformer, create the schema using the `GetOrCreateSchemaAsync` method provided in the context |
| 15 | +and add it to the OpenAPI document using the document's `AddComponent` method. |
| 16 | + |
| 17 | +<!-- In the docs, highlight the lines with the call to "GetOrCreateSchemaAsync" and "AddComponent" --> |
| 18 | +```csharp |
| 19 | +builder.Services.AddOpenApi(options => |
| 20 | +{ |
| 21 | + options.AddOperationTransformer(async (operation, context, cancellationToken) => |
| 22 | + { |
| 23 | + // Generate schema for error responses |
| 24 | + var errorSchema = await context.GetOrCreateSchemaAsync(typeof(ProblemDetails), null, cancellationToken); |
| 25 | + context.Document?.AddComponent("Error", errorSchema); |
| 26 | + |
| 27 | + operation.Responses ??= new OpenApiResponses(); |
| 28 | + // Add a "4XX" response to the operation with the newly created schema |
| 29 | + operation.Responses["4XX"] = new OpenApiResponse |
| 30 | + { |
| 31 | + Description = "Bad Request", |
| 32 | + Content = new Dictionary<string, OpenApiMediaType> |
| 33 | + { |
| 34 | + ["application/problem+json"] = new OpenApiMediaType |
| 35 | + { |
| 36 | + Schema = new OpenApiSchemaReference("Error", context.Document) |
| 37 | + } |
| 38 | + } |
| 39 | + }; |
| 40 | + }); |
| 41 | +}); |
| 42 | +``` |
0 commit comments