Why is HttpContext.Current null after await?
As @StephenCleary correctly pointed out, you need this in your web.config:
<httpRuntime targetFramework="4.5" />
When I was first troubleshooting this, I did a solution-wide search for the above, confirmed it was present in all my web projects and quickly dismissed it as the culprit. Eventually it occurred to me to look at those search results in full context:
<!--
For a description of web.config changes for .NET 4.5 see http://go.microsoft.com/fwlink/?LinkId=235367.
The following attributes can be set on the <httpRuntime> tag.
<system.Web>
<httpRuntime targetFramework="4.5" />
</system.Web>
-->
Doh.
Lesson: If you upgrade a web project to 4.5, you still need to get that setting in place manually.
I ran into this issue recently. As Stephen pointed out not setting explicitly the target framework can generate this issue.
In my case, our Web API was migrated to version 4.6.2 but the runtime target framework was never specified in the web config, so basically this was missing inside the <system.web> tag:
If you have doubts about the framework version you are running this may help: Add the following line on any of your Web API methods and set a breakpoint to verify what type is currently loaded at runtime and verify it is not a Legacy implementation:
You should see this (AspNetSynchronizationContext):
Instead of LegazyAspNetSynchronizationContext (Which was what I saw before adding the target framework):
If you go to the source code (https://referencesource.microsoft.com/#system.web/LegacyAspNetSynchronizationContext.cs) you will see that the Legacy implementation of this interface lacks of asynchronous support.
I spent a lot of time trying to find the source of the issue and Stephen´s response helped a lot. Hope this answer provides some more information about the issue.
Please ensure you are writing an ASP.NET 4.5 application, and targeting 4.5. async
and await
have undefined behavior on ASP.NET unless you are running on 4.5 and are using the new "task-friendly" synchronization context.
In particular, this means you must either:
- Set
httpRuntime.targetFramework
to4.5
, or - In your
appSettings
, setaspnet:UseTaskFriendlySynchronizationContext
totrue
.
More information is available here.