What is HttpContext, and why shouldn't you store or use it outside a request?
Quick Answer
HttpContext holds everything about the current request/response — User, Request, Response, Items, request services. It's tied to one request and is not thread-safe; it's recycled after the response. Capturing it in a field, a static, or a background task leads to NullReferenceExceptions or reading a different request's data.
HttpContext is the object that represents the current request and response — the user, the headers, the body, per-request state. It belongs to that one request, it's not thread-safe, and it gets recycled once the response is sent. So if I stash it in a field or a static, or hand it to a background task, I'll either get a null reference because it's been cleaned up, or I'll read data from a completely different request. The right pattern is to extract the values I need — user id, correlation id — into a simple object while I'm still on the request thread, and pass that around instead.
- Access it in a controller via the
HttpContextproperty; elsewhere injectIHttpContextAccessor— but only use it during the request. - For background work started from a request, copy the values you need (user id, correlation id) into a plain object before the work is queued.
IHttpContextAccessorin a singleton returns the context of whatever request last touched that thread — almost always a bug.- Don't pass
HttpContextinto services; pass the specific data (aCurrentUserabstraction, resolved per request).