Aspnetcore: Question about ActionResult<IEnumerable<Something>>

Created on 14 Jun 2018  路  2Comments  路  Source: dotnet/aspnetcore

I have been working on updating to .NET Core 2.1 on my api controllers. I've changed my IActionResult to ActionResult, and removed the Ok() and just return the T object now. But it doesn't seem to work with an IEnumerable.
Examples:
This works:

[HttpGet]
public async Task<IActionResult> GetUsersInPool(string poolId)
{
   // do work to get users

    return Ok(pool.Users);
}

This also works:

[HttpGet]
public async Task<ActionResult<IEnumerable<User>>> GetUsersInPool(string poolId)
{
    // do work to get users

    return Ok(pool.Users);
}

This also works

[HttpGet]
public async Task<ActionResult<List<User>>> GetUsersInPool(string poolId)
{
    // do work to get users

    return new List<User>(pool.Users);
}

This gives me a compile error:

[HttpGet]
public async Task<ActionResult<IEnumerable<User>>> GetUsersInPool(string poolId)
{
     // do work to get users

    return pool.Users;
}

Error: (on return pool.Users;)
CS0029 Cannot implicitly convert type 'System.Collections.Generic.ICollection<License.API.Entities.User>' to 'Microsoft.AspNetCore.Mvc.ActionResult<System.Collections.Generic.IEnumerable<License.API.Entities.User>>

Is there something I don't understand about ActionResult, or IEnumerable? Is the proper solution to covert to list first?

Most helpful comment

Is there something I don't understand about ActionResult, or IEnumerable?

ActionResult<T> uses an implicit operator to convert from T -> ActionResult<T>. C# does not allow implicit operators on interfaces (pool.Users in your case): https://stackoverflow.com/a/4280626. Converting it to a concrete type (new List<User>(pool.Users) or pool.Users.ToList()) would be the workaround here.

All 2 comments

Is there something I don't understand about ActionResult, or IEnumerable?

ActionResult<T> uses an implicit operator to convert from T -> ActionResult<T>. C# does not allow implicit operators on interfaces (pool.Users in your case): https://stackoverflow.com/a/4280626. Converting it to a concrete type (new List<User>(pool.Users) or pool.Users.ToList()) would be the workaround here.

Ahhhh, yes. This didn't occur to me.

Thanks for the response!

Was this page helpful?
0 / 5 - 0 ratings

Related issues

farhadibehnam picture farhadibehnam  路  3Comments

ermithun picture ermithun  路  3Comments

ipinak picture ipinak  路  3Comments

aurokk picture aurokk  路  3Comments

Kevenvz picture Kevenvz  路  3Comments