Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is HttpContext.Current null after await?

I have the following test WebAPI code, I don't use WebAPI in production but I made this because of a discussion I had on this question: WebAPI Async question

Anyways, here's the offending WebAPI method:

public async Task<string> Get(int id) {     var x = HttpContext.Current;     if (x == null)     {         // not thrown         throw new ArgumentException("HttpContext.Current is null");     }      await Task.Run(() => { Task.Delay(500); id = 3; });      x = HttpContext.Current;     if (x == null)     {         // thrown         throw new ArgumentException("HttpContext.Current is null");     }      return "value"; } 

I had hereto believed that the second exception is expected because when the await completes, it will likely be on a different thread where HttpContext.Current as a thread-static variable will no longer resolve to the appropriate value. Now, based on the synchronization context, it could actually be forced to go back to the same thread after the await but I'm not doing anything fancy in my test. This is just a plain, naive use of await.

In comments in another question I was told that HttpContext.Current should resolve after an await. There's even another comment on this question indicating the same. So what's true? Should it resolve? I think no, but I want an authoritative answer on this because async and await is new enough that I can't find anything definitive.

TL;DR: Is HttpContext.Current potentially null after an await?

like image 676
welegan Avatar asked Aug 22 '13 14:08

welegan


People also ask

Is HttpContext ever null?

Clearly HttpContext. Current is not null only if you access it in a thread that handles incoming requests.

What can I use instead of HttpContext current?

Instead of using HttpContext. Current , use the HttpContext provided as a property on the Page or Controller , or even better, you can simply use the Session property.

What is the use of HttpContext in asp net?

The HttpContext object constructed by the ASP.NET Core web server acts as a container for a single request. It stores the request and response information, such as the properties of request, request-related services, and any data to/from the request or errors, if there are any.


1 Answers

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 to 4.5, or
  • In your appSettings, set aspnet:UseTaskFriendlySynchronizationContext to true.

More information is available here.

like image 98
Stephen Cleary Avatar answered Oct 20 '22 00:10

Stephen Cleary