Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

HttpContext.Current is null when using async

Tags:

asp.net-mvc

I'm trying to call an async method that needs to read a file from the server. Whenever the method is async, HttpContext.Current becomes null. If I call it normally, it works fine. How do I go around this?

My code is:

System.IO.File.ReadAllText(HttpContext.Current.Server.MapPath(path))
like image 391
Shawn Mclean Avatar asked Mar 15 '11 20:03

Shawn Mclean


People also ask

Why HttpContext current is null?

Clearly HttpContext. Current is not null only if you access it in a thread that handles incoming requests. That's why it works "when i use this code in another class of a page".

How does HttpContext current work?

The HttpContext encapsulates all the HTTP-specific information about a single HTTP request. When an HTTP request arrives at the server, the server processes the request and builds an HttpContext object. This object represents the request which your application code can use to create the response.

What is HttpContext current in C#?

This property is a static property of the HttpContext class. 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.


1 Answers

The correct class to call is HostingEnvironment.MapPath(path);

Thanks for the tip bvs.

like image 188
brechtvhb Avatar answered Sep 17 '22 04:09

brechtvhb