Monday, September 9, 2013

ASP.NET Web API: HttpContext.Current is null inside Task

A few days ago, a colleague asked my help to solve an issue he had with ASP.NET Web API. His code looked like the following:

The problem was that HttpContext.Current was always null after switching to another task.

When I tried to reproduce the issue by building a similar sample on my computer, it just worked. The only difference between his code and mine was that I created an ASP.NET Web API 4.5 application, where he was still using ASP.NET 4.

So switching to .NET 4.5 solved the problem. But why? It seems that in ASP.NET 4.5, a task friendly synchronization context got introduced. This synchronization context ensures that the originel context is restored after leaving the await block.

So make sure that you either:

  • Set httpRuntime.targetFramework to 4.5, or
  • In your appSettings, set aspnet:UseTaskFriendlySynchronizationContext to true.

Some more information can be found here.

1 comment:

Robert F. Crocker said...

I promise next week will be more explicitly about perl. CodCow