C#C
C#2y ago
TheOnions

Swagger Schema generation with multiple TypedResults

I'm trying to generate Swagger documentation for a 3rd party API. I'd like it to include both the JSON schema and the yaml file as "200" response, but this code just generates a schema for the JSON object. How do I change it so that the yaml schema is generated too? I think somehow it depends on the order of the return signature which I don't understand. Related to this maybe? https://github.com/dotnet/aspnetcore/issues/55412#issuecomment-2091953405

using Microsoft.AspNetCore.Http.HttpResults;
using Microsoft.AspNetCore.Mvc;
using Test.Models;

var builder = WebApplication.CreateBuilder(args);

// Add services to the container.
// Learn more about configuring Swagger/OpenAPI at https://aka.ms/aspnetcore/swashbuckle
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen();

builder.Services.AddHttpClient("randomUserClient", client => 
{ 
    client.BaseAddress = new Uri("https://randomuser.me/api/"); 
});

var app = builder.Build();

// Configure the HTTP request pipeline.
if (app.Environment.IsDevelopment())
{
    app.UseSwagger();
    app.UseSwaggerUI();
}

app.UseHttpsRedirection();

app.MapGet("/user", async Task<Results<BadRequest,Ok<User>,FileContentHttpResult>> (IHttpClientFactory httpClientFactory, [FromQuery] string format) =>
{
    var client = httpClientFactory.CreateClient("randomUserClient");
    var response = await client.GetAsync($"?format={format}");
    if (!response.IsSuccessStatusCode) return TypedResults.BadRequest();
    return format switch {
        "json" => TypedResults.Ok(await response.Content.ReadFromJsonAsync<User>()),
        "yaml" => TypedResults.File(await response.Content.ReadAsByteArrayAsync(), contentType:"text/x-yaml"),
        _ => TypedResults.BadRequest()
    };
});

app.Run();
GitHub
Is there an existing issue for this? I have searched the existing issues Is your feature request related to a problem? Please describe the problem. When using the ProducesResponseType attribute to ...
Was this page helpful?