It is not clear from the original post that the HttpContext is actually missing. The HttpContext.User property HttpContext.User also be null at certain stages of the life cycle, which will give you the same exception. All other questions aside, you need to go through the source and see which part of the expression is actually null .
When you write code that refers to static methods / properties, such as HttpContext.Current , you should write to them, knowing that your code will not run when the methods / properties are really available. Usually you have something like this:
static string GetCurrentUserName() { HttpContext context = HttpContext.Current; if (context == null) return null; IPrincipal user = context.User; if (user == null) return null; return user.Identity.Name; }
Although I suspect that this will not solve your problem here, it will simply get rid of the exception. It is more likely that you call this method at a time or at a time when the context is simply inaccessible, for example, in a background thread, a static constructor or field initializer, or in the Application_BeginRequest method or in some similar place.
I can start by changing the static methods to class instance methods, which depend on the HttpContext instance (i.e. taken in the constructor). It's easy to fool yourself into thinking that methods like GetCurrentUserName are simple "utility" methods, but they really aren't, and it's usually not valid to call a method that references HttpContext.Current through a static property from anywhere you don't already have a reference instance on the same HttpContext (i.e. from the Page class). Most likely, if you start rewriting your classes as follows:
public class UserResolver { private HttpContext context; public UserResolver(HttpContext context) { if (context == null) throw new ArgumentNullException("context"); this.context = context; } public string GetUserName() { return (context.User != null) ? context.User.Identity.Name : null; } }
... then you will most likely find out very quickly where the chain is breaking, which will be the point at which you need to reference HttpContext.Current , because you cannot get it from anywhere else.
In this particular case, obviously, you can solve the problem by simply taking the NullReferenceException stack NullReferenceException to find out where / when the chain starts, so you don't need to make the changes that I described above - I just recommend a general approach that will help reduce such βmissingβ errors in the future.