asp.net-coreswagger

Swagger to display output type when using IEndpointRouteBuilder.MapGet and Results.Ok


I'm using .NET 8.0. If I have an endpoint like this:

IEndpointRouteBuilder app = //...
app.MapGet("users/foo", () =>
{
    return new UserBalance() { /* ... */ };
})
.WithName("GetFoo").WithOpenApi();

then the output contents for that endpoint show up in the Swagger documentation. However, if I wrap the output in Results.Ok before returning it:

IEndpointRouteBuilder app = //...
app.MapGet("users/foo", () =>
{
    return Results.Ok(new UserBalance() { /* ... */ });
})
.WithName("GetFoo").WithOpenApi();

then Swagger only says it returns a 200/OK -- the output contents no longer show up in Swagger. What is the syntax to tell Swagger what the output class of the endpoint is when I'm using Results.Ok? Thank you.


Solution

  • When you use Results.Ok to return a response, Swagger doesn't automatically know what type of data you're returning. To fix this, you need to explicitly tell Swagger what the response type is by using the Produces<T> method.

    using Microsoft.OpenApi.Models;
    using Microsoft.AspNetCore.Builder;
    using Microsoft.AspNetCore.Http;
    using Microsoft.AspNetCore.Routing;
    using Microsoft.Extensions.DependencyInjection;
    using Microsoft.Extensions.Hosting;
    
    
    var builder = WebApplication.CreateBuilder(args);
    
    // Add services to the container.
    
    builder.Services.AddControllers();
    builder.Services.AddEndpointsApiExplorer();
    builder.Services.AddSwaggerGen();
    
    
    var app = builder.Build();
    
    // Configure the HTTP request pipeline.
    if (app.Environment.IsDevelopment())
    {
        app.UseSwagger();
        app.UseSwaggerUI();
    
    }
    
    app.UseHttpsRedirection();
    app.MapGet("users/foo", () =>
    {
    return Results.Ok(new UserBalance() { UserId = 1, Balance = 100.50m });
    
    })
    .WithName("GetFoo")
    .Produces<UserBalance>(StatusCodes.Status200OK).WithOpenApi();
    
    
    app.UseAuthorization();
    
    app.MapControllers();
    
    app.Run();
    
    
    public class UserBalance
    {
        public int UserId { get; set; }
        public decimal Balance { get; set; }
    }
    

    enter image description here