C#C
C#3y ago
27 replies
Johannes M

❔ Using HttpContext outside of a controller/request pipeline (.NET 7)

Hi there I am currently busy with porting a "legacy" system from .NET Framework MVC to .NET Core MVC 7 and struggling with implementing some "global" state. Previously the project used the static accessor from System.Web but whenever I try using
IHttpContextAccessor
outside of a controller or a service I am calling inside of a controller I do not have access. I would like to have a class where I can store some static properties that I use throughout the project. Currently I am trying to use the Session State but when using it outside of the request pipeline the HttpContext will be null. I have some classes that are not used inside of a controller that need access to the HttpContext Session State. I have created a scoped service that I can call inside of controllers or request pipeline and the functionality works but once I step outside of the pipeline I have no access. Any advice is welcome.

Behavior trying to replicate:
public static int ClientID
{
    get { return Convert.ToInt32(HttpContext.Current.Session["clientid"]); }
    set { HttpContext.Current.Session["clientid"] = value; }
}
Was this page helpful?