Search code examples
c#asp.net-corehttpcontextminimal-apis

Why Visual Studio is telling me to replace argument with HttpContext when I use TypedResults.NotFound?


So, I got this little minimal api endpoint:

app.MapGet("/person/{name}", (string name) =>
    {
        var person = people.FirstOrDefault(p => p.Name.StartsWith(name));

        if (person == null)
            return (IResult)TypedResults.NotFound("Not found.");

        return TypedResults.Ok(person);
    }
);

I had to do (IResult) because of CS1678 'Parameter '1' is declared as type 'string' but should be 'Microsoft.AspNetCore.Http.HttpContext'' - i can't understand why is that the case with 'name' parameter.


Solution

  • The documentation mentions that

    TypedResults.Ok and TypedResults.NotFound are declared as returning different types and the compiler won't attempt to infer the best matching type.

    To use TypedResults, the return type must be fully declared, which when asynchronous requires the Task<> wrapper. Using TypedResults is more verbose, but that's the trade-off for having the type information be statically available and thus capable of self-describing to OpenAPI.

    In short, you need a Results<> wrapper.

    A possible way to adjust your code might look like below

    app.MapGet("/person/{name}",
        Results<NotFound<string>, Ok<Person>> (string name) =>
        {
            //var person = people.FirstOrDefault(p => p.Name.StartsWith(name));
            Person? person = null;
    
            return person is null
                ? TypedResults.NotFound("Not found.")
                : TypedResults.Ok(person);
        });