WebApi Async calls with IHttpActionResult

2014, Dec 31    

I’m currently working on a personal project where I am reusing a bunch of Task based api code from a Windows Phone project, and I am porting it over to WebApi.

In a WebApi controller, you can have something like the following

public IEnumerable<Product> GetAllProducts()
	return _someRepo.GetAllProducts();

And this will do what it says on the tin and return the requested data from the repo.

However, if the GetAllProducts method is asynchronous, and has it’s header defined something like

public async Task<IEnumerable<Product>> GetAllProductsAsync()

And you try to call it within a WebApi controller as we were trying to before, you get the following error

Cannot implicitly convert type ‘System.Threading.Tasks.Task<System.Collections.Generic.IEnumerable>' to 'System.Collections.Generic.IEnumerable'. An explicit conversion exists (are you missing a cast?) SomeController.cs 00 00 ProjectName

Makes sense, as you can’t convert something of type Task to something of type T.

To fix this, you can modify the controller method signiture to return IHttpActionResult and pass the returned data to the Ok class (which is of type OkNegotiatedContentResult, which returns as HttpStatusCode.OK if all was well).

The Controller class should remain inherited from ApiController. Don’t get thrown off by the presence of the other AsyncController base class.

The completed method now looks like

public async Task<IHttpActionResult> GetAllProducts()
	var products = await _someRepo.GetAllProducts();
    return Ok(products);

This is something that is probably quite obvious to most WebApi developers, but as a newbie this threw me for a few minutes, so hopefully it might help somebody else.