Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I access HttpContext.Current in Task.Factory.StartNew?

Tags:

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?

like image 878
Tim Tom Avatar asked May 19 '12 05:05

Tim Tom


People also ask

How do I find HttpContext current?

If you're writing custom middleware for the ASP.NET Core pipeline, the current request's HttpContext is passed into your Invoke method automatically: public Task Invoke(HttpContext context) { // Do something with the current HTTP context... }

What is the use of HttpContext current?

HttpContext is an object that wraps all http related information into one place. HttpContext. Current is a context that has been created during the active request. Here is the list of some data that you can obtain from it.

What is HttpContext current in C#?

The property stores the HttpContext instance that applies to the current request. The properties of this instance are the non-static properties of the HttpContext class. You can also use the Page. Context property to access the HttpContext object for the current HTTP request.


2 Answers

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);
like image 82
nemesv Avatar answered Nov 05 '22 13:11

nemesv


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.

like image 24
David Tischler Avatar answered Nov 05 '22 12:11

David Tischler