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:
public class WebApiController:ApiController | |
{ | |
public async Task Post([FromBody]string value) | |
{ | |
await DoSomething(); | |
Trace.WriteLine(RequestInfo.Instance.Data); | |
Debug.Assert(HttpContext.Current!=null); //Fails in ASP.NET MVC/Web API 4 | |
} | |
private Task DoSomething() | |
{ | |
return Task.Factory.StartNew(() => | |
{ | |
Trace.WriteLine(HttpContext.Current.Request.FilePath); | |
}).ContinueWith((t) => | |
{ | |
return Task.Delay(3000); | |
}); | |
} | |
} |
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
to4.5
, or - In your
appSettings
, setaspnet:UseTaskFriendlySynchronizationContext
totrue
.
Some more information can be found here.