I have a ASP.NET application using WCF REST running in IIS.
I need to store variables for the current HTTP request and I use HttpContext.Current.Items for that. I store some request Id that I set in my global.asax so I can use it deeper in my services. My services are doing some I/O operations so I recently changed them from synchronous to asynchronous. The problem is after the first await, the HttpContext.Current becomes null so I can't have access to my variables stored in HttpContext.Current.Items.
My global.asax:
protected void Application_BeginRequest(object sender, EventArgs e)
{
HttpContext.Current.Items["CurrentRequestId"] = SetRequestId();
}
My WCF contract:
[ServiceContract]
[AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Required)]
[ServiceBehavior(InstanceContextMode = InstanceContextMode.Single, ConcurrencyMode = ConcurrencyMode.Multiple)]
public class WcfService
{
[OperationContract]
[WebGet(UriTemplate = "Operation")]
public async Task<bool> Operation()
{
var context = HttpContext.Current; // Current context available here
await Task.Delay(1000).ConfigureAwait(true); // tried with both ConfigureAwait(true) and ConfigureAwait(false)
context = HttpContext.Current; // Current context is always null here
return true;
}
}
I tried to add those keys in my web.config file but it didn't change anything.
<appSettings>
<add key="aspnet:UseTaskFriendlySynchronizationContext" value="true"/>
<add key="wcf:disableOperationContextAsyncFlow" value="false"/>
</appSettings>
I am using .net 4.6.2
<httpRuntime targetFramework="4.6.2" />
Is it possible to keep the HttpContext.Current after awaiting an asynchronous method in WCF REST with ASP.NET? Is there an alternative to HttpContext.Current.Items I could use to achieve what I am trying to do?
EDIT: This is a simplified example but the HttpContext.Current is used way deeper and I would prefer not to have to gather it before the await and pass it all the way down to every single method.
This problem actually has nothing to do with asynchronous code; it has to do with retrieving a context variable from a (non-request) thread pool thread.
The technique recommended in the linked blog (wrapping the HttpContext and providing it to the worker thread) is extremely dangerous. HttpContext is designed to be accessed only from one thread at a time and AFAIK is not thread safe at all. So sharing it among different threads is asking for a world of hurt.
so i strongly suggest to you fetch every thing you need from HttpContext before your async method then use it.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With