1

I'm using HttpContext.Current.User to store some data about the client when the request is received.

I'm afraid that I might run into NullObjectReferenceException when HttpContext.Current is nulled unexpectedly and I'm trying to extract data from HttpContext.Current.User

The docomentation says about HttpContext.Current, that it:

Gets or sets the HttpContext object for the current HTTP request.

What are the cases where HttpContext.Current could be set to null?

Reed
  • 711
  • 9
  • 18

1 Answers1

3

It's null when your scope is not part of a Request.

Examples include:

If you're doing these things inside of a request you should be fine.

If you're using a background thread, or hooking some other part of aspnet which doesn't have the Request context then the static HttpContext might not be for you. There are other Request and Response contexts as well as Controller contexts which might be better. You should also consider injecting these things using a Container or, in the case where you don't know the execution context, wrap getting the user in an interface so you can deal with these context scenarios more cleanly.

This world is different in aspnet Core so I'm assuming you're referring to aspnet Framework.

Matt Kocaj
  • 10,718
  • 6
  • 47
  • 78
  • 1
    And also once the HTTP request is complete, i.e. once you have returned a response. – Rowan Freeman Nov 20 '19 at 08:13
  • And there's a bug (not sure resolved yet or not) in ASP.NET core where it is sometimes null in `async` methods when execution resumes after `await`. Let me see if I can find the link on GitHub for that. – Tanveer Badar Nov 20 '19 at 08:14