Why are my session variables not available when building the controller?

Using ASP.NET MVC when I try to retrieve the information stored in my session ["objectName"] from the constructor, I see that the session is not yet set, but as soon as the controller is constructed, the session contains the correct information.

public class ABCController : Controller { public ABCController() { var tmp = Session["Whatever"]; } //This line is null //But I know it has information public ActionResult Index() { var tmp = Session["Whatever"]; } //This works fine } 

thanks

+3
source share
2 answers

Session found in HttpContext. The HttpContext is provided to the controller as part of the ControllerContext. Since the ControllerContext is not passed as an argument to the constructor, it is not available until the class is created and the ControllerContext is assigned. It must be accessible, however, in any way on the controller. I'm not sure how you can expect class properties to be populated before calling the class constructor (unless they are properties of a static class, but it is not).

+8
source

Overwrite the method Initialize the base class of the controller. The request context is passed to this method. The session context is part of the request context.

  protected override void Initialize(System.Web.Routing.RequestContext requestContext) { base.Initialize(requestContext); var tmp = requestContext.HttpContext.Session["Whatever"]; } 

This method is called after the controller is created and before the action method is called.

+13
source

Source: https://habr.com/ru/post/1303805/


All Articles