如何解决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() ;
});
}
结果:
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。