Asp.net mvc - is a session available at any time during controller build?

I am trying to access the Session variables in the controller constructor and ControllerContext seems to always be null.

When are the earliest session variables available?

thanks!

Edit: Example:

in one controller:

public HomeController() { MyClass test = (MyClass)ControllerContext.HttpContext.Session["SessionClass"]; //ControllerContext always null } 

when debugging, controlcontext is always ALL. In a controller whose actionresult action is redirected to this controller, I have:

 Session["SessionClass"] = class; MyClass test = (MyClass )ControllerContext.HttpContext.Session["SessionClass"]; // this works fine! i can get varibale from session return RedirectToAction("Index", "Home"); 

So, at what point is ControllerContext installed? When can I access session variables?

+4
source share
2 answers

Override Initialize () :

 protected override void Initialize(System.Web.Routing.RequestContext requestContext) { base.Initialize(requestContext); requestContext.HttpContext.Session["blabla"] = "hello"; // do your stuff } 
+11
source

Session variables are already available in your controller's constructor call .

But those Sesison[] variables are not freely available anywhere in your controller class.


-> You need to call them either in the constructor or in the method of your controller.

In addition, these variables had to be set somewhere, or their values ​​would remain null .

According to your example, you need to set the Session["SessionClass"] key somewhere before calling it in the constructor:

 public ActionResult Details() { Session["SessionClass"] = new MyClass() { // Set your class properties }; return View((MyClass)Session["SessionClass"]); } 

Now we will undo this saved value from the session:

 public HomeController() { MyClass test = (MyClass)Session["SessionClass"]; // Do stuff with `test` now } 

This should work fine in your controller.

Greetings

-2
source

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


All Articles