ActionResult<IEnumerable<T>> 必须 return 一个列表<T>

ActionResult<IEnumerable<T>> has to return a List<T>

使用 ASP.NET Core 2.1 获取以下代码:

[HttpGet("/unresolved")]
public async Task<ActionResult<IEnumerable<UnresolvedIdentity>>> GetUnresolvedIdentities()
{
   var results = await _identities.GetUnresolvedIdentities().ConfigureAwait(false);
   return results.ToList();
}

GetUnresolvedIdentities() returns IEnumerable<UnresolvedIdentity> 开始我就认为我可以 return

return await _identities.GetUnresolvedIdentities().ConfigureAwait(false);

除了我不能,因为我得到这个错误:

CS0029 Cannot implicitly convert type 'System.Collections.Generic.IEnumerable<Data.Infrastructure.Models.UnresolvedIdentity>' to 'Microsoft.AspNetCore.Mvc.ActionResult<System.Collections.Generic.IEnumerable<Data.Infrastructure.Models.UnresolvedIdentity>>'

我需要 .ToList(),这很烦人,因为它是 2 行而不是 1 行。

为什么 ActionResult<T> 不能弄清楚 GetUnresolvedIdentities() return 是一个 IEnumerable<> 而只是 return 那个?

GetUnresolvedIdentities的签名是:

Task<IEnumerable<UnresolvedIdentity>> GetUnresolvedIdentities();

从 msdn 获取此文档: https://docs.microsoft.com/en-us/aspnet/core/web-api/action-return-types?view=aspnetcore-2.1#actionresultt-type

C# doesn't support implicit cast operators on interfaces. Consequently, conversion of the interface to a concrete type is necessary to use ActionResult<T>.

您可以使用 Ok(...)

以相对整洁的方式解决此问题
[HttpGet]
public ActionResult<IEnumerable<MyDTOObject>> Get() => Ok(Repo.GetObjects());

[HttpGet]
public async Task<ActionResult<IEnumerable<MyDTOObject>>> GetAsync() => Ok(await Repo.GetObjectsAsync());

假设 GetObjects()GetObjectsAsync() return 分别是 IEnumerable<MyDTOObject>Task<IEnumerable<MyDTOObject>> - 允许您跳过 .ToList().ToListAsync().