ActionResult <ienumerable <t >>必须返回一个List <t>

时间:2018-08-08 08:55:15

标签: c# asp.net-core actionresult 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();
}

GetUnresolvedIdentities()返回IEnumerable<UnresolvedIdentity>以来,我一直以为我可以返回

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

除了我不能,因为出现此错误:

  

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

1 个答案:

答案 0 :(得分:19)

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

  

C#不支持接口上的隐式强制转换运算符。   因此,将接口转换为具体类型是   必须使用ActionResult<T>