realPro
realPro

Reputation: 1856

HttpContext is null after await in in ASP.NET 4.8

I am trying to write async code in asp.net 4.8 but and the problem is that HttpContext is null after returning from await. This means that the async code works correctly which is good, but the HttpContext is needed by the original code. From the comments in below answer by Darin Dimitrov it shows that HttpContext is having this issue since 4.6.1. Why is HttpContext.Current null after await?

var domains = HttpContext.Current.Cache.Get("domains") as Dictionary<String, Domains>;


            if (domains == null)
            {
                var x = await TrackingMethods.GetTableForCacheAsync().ConfigureAwait(false);
                domains = x.domains;
        }

/// HttpContext.Current is null here

Upvotes: 1

Views: 1556

Answers (1)

Stephen Cleary
Stephen Cleary

Reputation: 457362

ConfigureAwait(false) means "don't resume on the captured context". By specifying ConfigureAwait(false), your code is telling the runtime that it doesn't need the ASP.NET request context. But your code does need the ASP.NET request context, since it depends on HttpContext.Current. So using ConfigureAwait(false) here is wrong.

If I don't use ConfigureAwait(false) the code will not run.

This is likely because your code is blocking further up the call stack, causing a deadlock. The ideal solution is to remove the blocking - i.e., use async all the way. Using async all the way is preferable to blocking with ConfigureAwait(false).

However, there are a handful of scenarios where this isn't possible. For example, ASP.NET 4.8 doesn't have proper asynchronous support for MVC action filters or child actions. If you're doing something like this, then you have a couple of options:

  • Make it synchronous all the way instead of async all the way.
  • Keep the blocking-over-async-with-ConfigureAwait(false) antipattern but copy out everything your code needs from HttpContext.Current first and pass that data as explicit parameters so the code no longer has a dependency on the ASP.NET request context.

Upvotes: 6

Related Questions