POST request return empty response
Asked Answered
B

1

2

I've got a minimal API with a POST request /query expecting a raw json to search in mongodb

app.MapPost("/query", async (HttpContext context) => await FreeQuery(context));

FreeQuery is async and it returns an IEnumerable. But the async version causes internalserver error

async Task<IEnumerable<PreOrder>> FreeQuery(HttpContext context)
{
    using (StreamReader reader = new StreamReader(context.Request.Body, Encoding.UTF8))
    {
        string query = await reader.ReadToEndAsync();

        var filter = BsonDocument.Parse(query);

        var result = _collection.Find(filter);

        var list = EnumFromBson<PreOrder>(result);

        Console.WriteLine(list.Count());

        return list;
    }
}

list.Count() returns 34 but when reading the result back on the client it's an empty string! Content-Length of the response is zero too.

How do I get a valid List back at the client?

It does work in a GET request (non async) btw

IEnumerable<PreOrder> FindByField(string field, string value)
{
    var filter = Builders<BsonDocument>.Filter.Eq(field, value);
    var result = _collection.Find(filter);

    var list = EnumFromBson<PreOrder>(result);

    return list;
}
Borras answered 1/11, 2022 at 9:37 Comment(1)
There was a bug for cases when method group calls used for handler lead to empty response - see here but it was other way around.Luciferase
L
2

Add dummy parameter to the handler:

app.MapPost("/query",
    async (HttpContext context, ILogger<Program> _) => await FreeQuery(context));

There was a very similar bug (should be fixed in .NET 7) for Map async handlers with one HttpContext parameter when used via method group invocations which resulted in empty response from Minimal API endpoint. I will check later if the fix for previous issue also fixes this one.

UPD

Issue was not actually fixed (github issue for .NET 7).

Luciferase answered 1/11, 2022 at 10:19 Comment(1)
yep thats it. There's 2 overloads of MapPost apparently and with 1 param the wrong one is taken. I added cancellationtoken btw which can be passed to mongodb too so it has use tooBorras

© 2022 - 2025 — McMap. All rights reserved.