Wednesday, March 9, 2016

Using the async and await keywords with ASP.NET Web API

If you are looking for a Microsoft/MSDN article on how to use the async and await keywords with ASP.NET Web API Controller methods you will not find such an article very readily.

If you are looking to call your ASP.NET Web API Controller methods asynchronously from a .NET Client, then you can refer to this article: http://www.asp.net/web-api/overview/advanced/calling-a-web-api-from-a-net-client

However, if you actually want your Web API Controller methods to be decorated with the async keyword, then you will want to refer to this article: http://www.codeproject.com/Tips/805923/Asynchronous-programming-in-Web-API-ASP-NET-MVC

If you need to be able to call a synchronous method asynchronously, you can use Task.Run as follows:


return await Task.Run(() => DoIt());

Therefore, your final ASP.NET Web API Methods will look something like this:


public async Task<IHttpActionResult> MyAsyncGet()
        {
            return await Task.Run(() => DoIt());
        }

private IHttpActionResult DoIt()
{
   return Content(HttpStatusCode.OK, "some string");
}

No comments:

Post a Comment