Search code examples
asp.net-coregenericsactionresult

IActionResult The type arguments for method cannot be inferred from the usage


I have an action wrapper method for my ASP.NET CORE web api

        public async Task<TResponse> ThrowIfNullActionWrapper<TResponse>(Func<Task<TResponse>> func)
            where TResponse : IActionResult
        {
            try
            {
                // business logic
                return await func();
            }
            catch (ValueNullCheckFailureException)
            {
                return (TResponse)(Object)new NotFoundResult();
            }
            catch (Exception)
            {
                throw;
            }
        }

When I have different return types like below, I got The type arguments for method cannot be inferred from the usage error.

        [HttpGet("{id}")]
        public async Task<ActionResult<MyDto>> Get(Guid id)
        {
            return await ThrowIfNullActionWrapper(async () => { 
                // some codes...
                if (xxxxx)
                {
                    return NotFound();
                }
                // some codes...
                return Ok(dto);
            });
        }

If I remove the line return NotFound();, the error will go away.

It seems the different return types of OK() and NotFound() methods caused this issue. But both of them inherits from IActionResult.

Can I use OK() and NotFound() methods at same time without the type arguments for method cannot be inferred from the usage issue?


Solution

  • According to your description, I suggest you could add as StatusCodeResult after the NotFound() method to avoid different return type for ThrowIfNullActionWrapper.

    More details, you could refer to below codes:

        [HttpGet("{id}")]
        public async Task<ActionResult<RouteModel>> Get(Guid id)
        {
            return await ThrowIfNullActionWrapper(async () => {
                // some codes...
                if (1 == 0 )
                {
                    return NotFound() as StatusCodeResult;
                }
                // some codes...
                return  Ok()  ;
            });
        }
    

    Result:

    enter image description here