In my HomeController when a particular action is called, I can see when debugging that the Session is there. However when the HomeController action instantiates another controller programmatically and accesses a property on it, that property tries to access the session and it is null.
Something like this:
public class HomeController : Controller
{
public PartialViewResult SomeAction()
{
// When debugging, I can break here and
// see the Session in the Immediate Window
var a = new AnotherController();
var b = a.SomeProperty;
}
}
public class AnotherController : Controller
{
public object SomeProperty
{
get
{
// Session is null here
return Session["MyProperty"];
}
}
}
Edit:
Not sure if this is important, but forgot to mention that SomeAction is called via ajax. Since the Session is available in that action though, I wouldn't think this is relevant.
答案 0 :(得分:2)
It's not a good idea to create controller "by hands". You should refactor your code to avoid this. Move properties to service and inject it. Maybe you need to create custom controller factory.
答案 1 :(得分:2)
public class HomeController : Controller
{
public PartialViewResult SomeAction()
{
// When debugging, I can break here and
// see the Session in the Immediate Window
var b = SessionHelper.SomeProperty;
}
}
public class SessionHelper
{
public static object SomeProperty
{
get
{
return System.Web.HttpContext.Current.Session["MyProperty"];
}
}
}
答案 2 :(得分:1)
If you are using Session, you might be able to get it anywhere. YOu don't need to instantiate another controller to read it:
public class HomeController : Controller
{
public PartialViewResult SomeAction()
{
//you can access the session anywhere
var s = Session["MyProperty"] as YourTypeHere;
}
}
You also can create a static class to hold a const string that represents the Session's name.