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

狂风中的少年 提交于 2019-12-18 12:55:22

问题


Take the following code using ASP.NET Core 2.1:

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

I would have thought since GetUnresolvedIdentities() returns IEnumerable<UnresolvedIdentity> that I could just return

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

Except I can't, as I get this error:

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>>'

I need the .ToList(), which is annoying as it's 2 lines rather than 1.

Why can't ActionResult<T> figure out that GetUnresolvedIdentities() returns an IEnumerable<> and just return that?

The signature of GetUnresolvedIdentities is:

Task<IEnumerable<UnresolvedIdentity>> GetUnresolvedIdentities();

回答1:


Take this documentation from 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>.



来源:https://stackoverflow.com/questions/51742520/actionresultienumerablet-has-to-return-a-listt

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!