I'm working on a Web API, which purely has synchronous code running. I wanted to turn certain methods async and run some parallel tasks. The problem is that after turning the methods async, the HttpContext.Current becomes null, when it's referred to subsequently in the async methods.
The Web API has a filter put on certain controller methods that looks something like this:
public class AuthenticationTokenFilter : ActionFilterAttribute
{
public override void OnActionExecuting(HttpActionContext actionContext)
{
var email = // Get some stuff from the request and do some things with it.
var id = // Get some stuff from the request and do some things with it.
System.Web.HttpContext.Current.Items.Add("Property1", email);
System.Web.HttpContext.Current.Items.Add("Property2", id);
}
Subsequently, an injected class called something like a ContextProvider will refer directly to the HttpContext to retrieve these properties. However, when calling the provider from the async methods, the context is null, and we get a null reference is exception.
I've read several posts on this, and the solution is not obvious to me. I've tried setting the following in the configuration file:
<add key="aspnet:UseTaskFriendlySynchronizationContext" value="true" />
and I've ensured that a higher version than .NET 4.5 is targeted(it uses 4.6.1).
Others seem to suggest that you can invoke the async methods with the HttpContext, but I don't know how to do it, and would prefer not to have to invoke the HttpContext in every single method awaited in this chain.