Search code examples
c#.netasp.net-coretuplesminimal-apis

return a Tuple from minimal API


I'm trying to return a Tuple in a minimal API, it boils down to this:

app.MapPost("/colorkeyrect", () => server.ColorkeyRect());

public (int x, int y, int w, int h) ColorkeyRect()
{
  return (10, 10, 10, 10);
}

But the data that is sent over the wire is an empty json:

content = await response.Content.ReadAsStringAsync();

'{}'

var obj = JsonConvert.DeserializeObject<(int, int, int, int)>(content);

So this becomes (0, 0, 0, 0) instead of (10, 10, 10, 10).

Is it even possible to return a Tuple in a Minimal API app? What to do to get a valid object returned when only relying on primitive types?


Solution

  • Yes, it is possible. By default System.Text.Json does not serialize fields, and value tuple elements are fields (ValueTuple), so you need to configure JsonOptions (be sure to use "correct" ones - for Minimal APIs from Microsoft.AspNetCore.Http.Json namespace):

    builder.Services.Configure<JsonOptions>(options => options.SerializerOptions.IncludeFields = true);
    

    But I would argue that it is a bit useless, value tuple names is a piece of information which is not represented at runtime so you will get response like:

    {"item1":1,"item2":2}
    

    I would recommend to use either anonymous type or just create a record (record struct if really needed), it is very easy to create a new DTO type nowadays. And with target-typed new expressions it is not a big change in the method also:

    record Responce(int X, int Y, int W, int H); // or record struct Responce ...
    
    public Responce ColorkeyRect()
    {
        return new (10, 10, 10, 10);
    }