Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Delegate 'RequestDelegate' does not take 2 arguments - ASP.NET Core 8 Minimal API

This is my Minimal API (.NET 8):

app.MapPost("check", async ([FromBody] UserClaims claims, ApplicationDbContext dbContext) =>
{
    var result = await dbContext.Users.SingleOrDefaultAsync(x => x.Phone == claims.Phone);

    if (result is null)
        return TypedResults.NotFound();

    return TypedResults.Ok();
});

enter image description here

I am getting a CS1593 error under my lambda expression.

What am I doing wrong ?

Removing the following part from my API solves the problem:

if (result is null)
    return TypedResults.NotFound();

Also, replacing TypedResults with Results solves the problem. Is there a restriction when using TypedResults?

like image 529
Amirhessam Pourhossein Avatar asked Mar 07 '26 10:03

Amirhessam Pourhossein


2 Answers

While you can specify the delegate return type I would argue that switching to Results would be easier (as you discovered):

app.MapPost("check", async ([FromBody] UserClaims claims, ApplicationDbContext dbContext) =>
{
    // ...

    if (result is null)
        return Results.NotFound();

    return Results.Ok();
});

Both return the same type - IResult so the compiler can infer correct return type.

Also in this particular case you can use ternary operator. If you want to keep the TypedResults it can reduce clutter a bit. For example with IResult (though arguably not much reason to do so):

app.MapPost("check", async ([FromBody] UserClaims claims, ApplicationDbContext dbContext) =>
{
    // ...

    return result is null 
        ? (IResult)TypedResults.NotFound() 
        : TypedResults.Ok();
});

Or Results<NotFound, Ok>:

app.MapPost("check", async ([FromBody] UserClaims claims, ApplicationDbContext dbContext) =>
{
    var result = claims;

    return result is null 
        ? (Results<NotFound, Ok>) TypedResults.NotFound() 
        : TypedResults.Ok();
});

Also check out this answer and discussions in the comments.

like image 200
Guru Stron Avatar answered Mar 08 '26 23:03

Guru Stron


From the TypedResults docs,

To use TypedResults, the return type must be fully declared, which when asynchronous requires the Task<> wrapper.

app.MapPost("check", async Task<Results<Ok, NotFound>> ([FromBody] UserClaims claims, ApplicationDbContext dbContext) =>
{
    var result = await dbContext.Users.SingleOrDefaultAsync(x => x.Phone == claims.Phone);

    if (result is null)
        return TypedResults.NotFound();

    return TypedResults.Ok();
});
like image 25
Yong Shun Avatar answered Mar 08 '26 23:03

Yong Shun



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!