ActionResult <IEnumerable <T >>必须返回List <T>

Stu*_*art 14 c# actionresult asp.net-core asp.net-core-2.1

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

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

因为我本来以为GetUnresolvedIdentities()回报IEnumerable<UnresolvedIdentity>,我可以只返回

return await _identities.GetUnresolvedIdentities().ConfigureAwait(false);
Run Code Online (Sandbox Code Playgroud)

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

CS0029无法将类型隐式转换 'System.Collections.Generic.IEnumerable<Data.Infrastructure.Models.UnresolvedIdentity>''Microsoft.AspNetCore.Mvc.ActionResult<System.Collections.Generic.IEnumerable<Data.Infrastructure.Models.UnresolvedIdentity>>'

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

为什么无法ActionResult<T>弄清楚GetUnresolvedIdentities()返回IEnumerable<>并返回那个?

签名GetUnresolvedIdentities是:

Task<IEnumerable<UnresolvedIdentity>> GetUnresolvedIdentities();
Run Code Online (Sandbox Code Playgroud)

V0l*_*dek 22

就拿从MSDN本文档: https://docs.microsoft.com/en-us/aspnet/core/web-api/action-return-types?view=aspnetcore-2.1#actionresultt-type

C#不支持接口上的隐式转换运算符.因此,需要将接口转换为具体类型ActionResult<T>.


Pho*_*cUK 6

您可以使用以下方法以相对简洁的方式解决此问题Ok(...)

[HttpGet]
public ActionResult<IEnumerable<MyDTOObject>> Get() => Ok(Repo.GetObjects());

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

假设GetObjects()和分别GetObjectsAsync()返回 aIEnumerable<MyDTOObject>Task<IEnumerable<MyDTOObject>>- 允许您跳过.ToList()or .ToListAsync()