Tuesday, January 7, 2014

HttpContext.Current.GetOwinContext().Authenticate returns System.NullReferenceException when used in web api ie. Apicontroller.

The reason is the original context is not restored after leaving the await block. This is when used with task parallelism await async block.

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.