Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
277 views
in Technique[技术] by (71.8m points)

ASP.NET MVC - Session is null

I have an MVC3 application on .net4 that its session working in the dev Environment, but not in the production.
In the production I logged the sessionID and the it is the same in the moment I Set and Get from the session.

When I try to get the session I am getting Null Exception.

This is how I access the session:

public static class HandlersHttpStorage
{
    public static string TestSession
    {
        get
        {
            return HttpContext.Current.Session["time"];//This is null
        }
        set
        {
            HttpContext.Current.Session.Add("time", value);//DateTime.Now.ToString()
        }
    }
}

What's makes me worried is that the behavior in the production is different than the development, even though the web.config is the same.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Solution 1:

Link: HttpContext.Current.Session is null when routing requests

Got it. Quite stupid, actually. It worked after I removed & added the SessionStateModule like so:

<configuration>
  ...
  <system.webServer>
    ...
    <modules>
      <remove name="Session" />
      <add name="Session" type="System.Web.SessionState.SessionStateModule"/>
      ...
    </modules>
  </system.webServer>
</configuration>

Simply adding it won't work since "Session" should have already been defined in the machine.config.

Now, I wonder if that is the usual thing to do. It surely doesn't seem so since it seems so crude...

Solution 2:

Link: HttpContext.Current.Session null item

sessionKey may be changing, you probably only need to do:

HttpContext.Current.Session["CurrentUser"]

Or the session may be expiring, check the timeout:

http://msdn.microsoft.com/en-us/library/h6bb9cz9(VS.71).aspx

Or you may be setting the session value from somewhere else, normally i control access to Session/Context object through one property

static readonly string SESSION_CurrentUser = "CurrentUser";

public static SiteUser Create() {     
 SiteUser.Current = new SiteUser();      
 return SiteUser.Current;
}

public static SiteUser Current {     
 get {         
  if (HttpContext.Current.Session == null || HttpContext.Current.Session[SESSION_CurrentUser] == null) {             
   throw new SiteUserAutorizationExeption();         
  }          
  return HttpContext.Current.Session[SESSION_CurrentUser] as SiteUser;     
 } 
 set {
  if (!HttpContext.Current.Session == null) {
   HttpContext.Current.Session[SESSION_CurrentUser] = value;
  }
 }
} 

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...