I want to access HttpContext.Current in my asp.net application within
Task.Factory.Start(() =>{
//HttpContext.Current is null here
});
How can I fix this error?
Answers:
Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.
Method 1
Task.Factory.Start will fire up a new Thread and because the HttpContext.Context is local to a thread it won’t be automaticly copied to the new Thread, so you need to pass it by hand:
var task = Task.Factory.StartNew(
state =>
{
var context = (HttpContext) state;
//use context
},
HttpContext.Current);
Method 2
You could use a closure to have it available on the newly created thread:
var currentContext = HttpContext.Current;
Task.Factory.Start(() => {
// currentContext is not null here
});
But keep in mind that a task can outlive the lifetime of the HTTP request and could lead to funny results when accessing the HTTPContext after the request has completed.
Method 3
As David pointed out, HttpContext.Current will not work all the time. In my case, about 1 of 20 time, CurrentContext will be null. End up with below.
string UserName = Context.User.Identity.Name;
System.Threading.Tasks.Task.Factory.StartNew(() =>
{
UserName ...
}
All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0