1

In my ASP.NET MVC web application, one of my Controller action methods invokes some code that relies on getting information from the current HttpContext. That code is not part of my Controller, so it can't use Controller.HttpContext - instead it uses System.Web.HttpContext.Current. (I know that's a bad idea, but I'm not in a position to change that).

This was all working until I added an await to my Controller action method. Now, when I subsequently invoke the code that uses System.Web.HttpContext.Current it fails because HttpContext.Current is null.

I did some reading and found something that said that System.Web.HttpContext.Current is only set on a the thread that's processing a web request. That makes sense. However, I'm surprised that simply using await is enough to switch to a different thread.

My understanding is that using await without ConfigureAwait(false) (as in var result = await myTask;) ensures that the code following the await is invoked using the SynchronizationContext in effect prior to the await.

I mentally equated this with "running on the same thread" - that is, the code after the await would run on the same thread as the code before the await (even though the Task being awaited might be executed on a different thread). Turns out that's not true - the Thread.CurrentThread.ManagedThreadId is different before and after the await.

Oddly, the behaviour I'm seeing is the opposite of what's described in this question.

I'm confused - can anyone shed any light on whether (a) I should expect System.Web.HttpContext.Current to be null after any await call, and (b) whether there's any way to make the code after the await resume on the same thread so that it's not null?

Gary McGill
  • 26,400
  • 25
  • 118
  • 202

1 Answers1

2

OK, I found this answer on a similar question. Apparently this behaviour was caused by the "quirks mode" of ASP.NET. :-(

Adding the following to my web.config fixed the problem by ensuring that the code after the await was executed on the same thread, and so HttpContext.Current was non-null.

<add key="aspnet:UseTaskFriendlySynchronizationContext" value="true"/>
Gary McGill
  • 26,400
  • 25
  • 118
  • 202
  • What runtime are you using? – Paulo Morgado Oct 15 '20 at 17:23
  • 1
    @PauloMorgado: the project was originally for ASP.NET v4 (or perhaps earlier) and is now using ASP.NET v4.5 or later. Because the project was upgraded rather than created afresh, the `` entry wasn't added to the web.config. That or the entry in my answer both fix the issue I was having. – Gary McGill Oct 16 '20 at 10:42