开发者

asp.net mvc is Session available at any point during controller construction?

i am trying to access Session variables in the constructor of a controller and ControllerContext it seems is always null.

When is the earliest the session variables are available?

thanks!

Edit: Example:

开发者_高级运维

in one controller:

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

when debugging, controllercontext is ALWAYS null. In the controller whose actionresult redirects 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 actually set? When can I access session variables?


Override Initialize():

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


Session variables are already available in the constructor call of your controller.

But those Sesison[] variables aren't freely available anywhere in your controller class.


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

Furthermore those variables should have been set somewhere or their vaues will stay null.

According to your example you'll need to set your 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'll unbox that saved value from the session:

public HomeController()
{
  MyClass test = (MyClass)Session["SessionClass"];

  // Do stuff with `test` now
}

This should work fine within your controller.

Cheers

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜