Nathan1
20 days agoNew Member
Json and Xml example with inheritance
Hi,
My goal is to have different examples for my my json and my xml response.
So when you switch from json to xml in the swagger UI it should show a different example.
I tried doing it with a IOperationFilter, but I'm unable to. Setting the example this way seems to always override the previous set example.
public void Apply(OpenApiOperation operation, OperationFilterContext context)
{
// 1. Iterate through all responses (200, 201, 400, etc.)
foreach (var response in operation.Responses)
{
// 2. Find the DTO type for this specific response code
Type? responseType = context.ApiDescription.SupportedResponseTypes
.FirstOrDefault(x => x.StatusCode.ToString() == response.Key)?
.Type;
if (responseType == null) continue;
foreach (var contentTypeKey in response.Value.Content.Keys)
{
var mediaType = response.Value.Content[contentTypeKey];
if (contentTypeKey.Contains("application/json"))
{
// Set the example ONLY for JSON
mediaType.Example = JsonSerializer.SerializeToNode("{\"exampleInstance\":true}");
}
else if (contentTypeKey.Contains("application/xml"))
{
// Set the example ONLY for XML
var xmlString = "<TEST>exampleInstance</TEST>";
mediaType.Example = JsonValue.Create(xmlString);
}
}
}
}Am I missing something?
Kind regards