Search code examples
.netexceptiondeploymenthttpcontext

HttpContext.Current.Server threw an exception of type System.NullReferenceException when I deploy to my server


For some reason after deploying the same code that works perfectly on localhost to my server this line fails:

private static string nodePath = HttpContext.Current.Server.MapPath(ConfigurationManager.AppSettings["NodeJS.Path"]);

The original exception is System.TypeInitializationException: The type initializer for 'Turcos.App.Components.AsyncFileExporter' threw an exception. But it's clear to see that the exception is thrown because HttpContext.Current is null.

I understand that HttpContext.Current can be null sometimes (https://stackoverflow.com/a/6861575/1519464) but why it's working on my local and not on the server? What's even more weird is that the code that I prevously had on my server was using HttpContext.Current and it worked perfectly. What could have changed that stoped this from working?


Solution

  • Okay, so I finally found the cause. After deploying, my class in question was being called via a .net API controller, so it seems that the when HttpContext.Current was trying to be used in this line: private static string nodePath = HttpContext.Current.Server.MapPath(ConfigurationManager.AppSettings["NodeJS.Path"]);, it wasn't initialized so it threw the exception.

    The solution: after the deployment, the first thing I did was loading index.html and it seems that it triggered a proper initialization of all static attributes as the issue stopped happening. At the end of the day, it was a tricky initialization/ lifecycle issue