Home > Software engineering >  Minimal API with async static method
Minimal API with async static method

Time:11-30

When we create something like this in NET 7:

app.MapPost("/test", SomeEndpoint.Test);

This is my SomeEndpoint.Test:

public static class SomeEndpoint
{
    public static IResult Test(HttpContext httpContext)
    {
        var form = httpContext.Request.ReadFormAsync().Result;
        return Results.Ok(form);
    }
}

then anything works well. But I want to have it async, so now my SomeEndpoint.Test looks as below:

public static class SomeEndpoint
{
    public static async Task<IResult> Test(HttpContext httpContext)
    {
        var form = await httpContext.Request.ReadFormAsync();
        return Results.Ok(form);
    }
}

Boom. That's not working, I always get 200 OK response (even if I change my Results.Ok to Results.BadRequest). What am I doing wrong?

CodePudding user response:

The problem you are seeing appears to be related to the fact that you are passing extra arguments at all. Removing the HttpContext also causes your sample to work.

When passing parameters to an async static method like that, it seems that you are forced to provide the CancellationToken parameter otherwise it won't match for Task-based method groups.

The following works:

public static class SomeEndpoint
{
    public static async Task<IResult> Test(
        HttpContext httpContext, 
        CancellationToken token)
    {
        var form = await httpContext.Request.ReadFormAsync(token);
        return Results.Ok(form);
    }
}
  • Related