I have been working on updating to .NET Core 2.1 on my api controllers. I've changed my IActionResult to ActionResult
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?
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!
Most helpful comment
ActionResult<T>
uses an implicit operator to convert fromT
->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)
orpool.Users.ToList()
) would be the workaround here.