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

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?
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.
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();
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With