Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Minimal API with async static method

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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?

>Solution :

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);
    }
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading