Home > Back-end >  POST request return empty response
POST request return empty response

Time:11-01

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. No asyn causes internalserver error And it returns an IEnumerable<PreOrder.

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;
}

CodePudding user response:

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. I will check later if the fix for previous issue also fixes this one.

  • Related