IActionResult无法从用法中推断出方法的类型参数

问题描述

我为我的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;
            }
        }

我有如下所示的不同返回类型时,我遇到了The type arguments for method cannot be inferred from the usage错误

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

如果我删除return NotFound();行,该错误将消失。

似乎OK()NotFound()方法的不同返回类型导致了此问题。但是它们都继承自IActionResult

是否可以同时使用OK()NotFound()方法而不会出现type arguments for method cannot be inferred from the usage问题?

解决方法

根据您的描述,建议您在NotFound()方法之后添加为StatusCodeResult,以避免ThrowIfNullActionWrapper的返回类型不同。

更多详细信息,您可以参考以下代码:

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

结果:

enter image description here