Shawn Mclean
Shawn Mclean

Reputation: 57479

HttpContext.Current is null when using async

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))

Upvotes: 11

Views: 7538

Answers (3)

brechtvhb
brechtvhb

Reputation: 1048

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

Thanks for the tip bvs.

Upvotes: 3

Arkadiusz Kałkus
Arkadiusz Kałkus

Reputation: 18443

Here - http://blogs.msdn.com/b/webdev/archive/2012/11/19/all-about-httpruntime-targetframework.aspx - is a documentation about HttpContext used with async/await.

To cut a long story short you need to do one of two things:

  • Set key in application settings: <add key="aspnet:UseTaskFriendlySynchronizationContext" value="true" />
  • Set your framework to 4.5

Upvotes: 1

bvs
bvs

Reputation: 109

Use HostedEnvironment.MapPath instead:

System.IO.File.ReadAllText(HostedEnvironment.MapPath(path))

Upvotes: 2

Related Questions