简体   繁体   中英

Maintaining session in a class C#

I am trying to maintain session in a class for MVC application . Below is the code which i used get and set session in a variable. But whenever i am accessing this variable after set, it is giving null.

public static class MySession
{
    public static string MyVar
    {
        get
        {
            return HttpContext.Current.Session["MyVar"] == null ? "" : HttpContext.Current.Session["MyVar"].ToString();
        }
        set
        {
            HttpContext.Current.Session["MyVar"] = value;
        }
    }
}

And I used to set as MySession.MyVar="testData";

But when i access string str = MySession.MyVar;

it gives null value. Does anybody know why my session is not stored?

Session variables are very much exposed to being null, that is each time a new session is created by user, browser, network or application itself. That is why, it is very much recommended to wrap it around with if...else block.

if(Session["key"] != null) {
   // Variable exists for the session
   // use variable
} else {
   // Variable doesn't exist in the session
   // create and user variable
}

However, if still you always get a null , then you should check what is going wrong. My bet is that there is some other code or process that terminates the previous sessions and restarts them. You should know you can programmatically also remove all sessions, that might also cause this problem.

Also, Session variables can be used and served using a class, there is no problem in that. Just make sure that the collection Session isn't being refreshed.

My guess is you have not enabled session state.

<system.web>
    <sessionState mode="InProc" timeout="60"/>
<system.web>

Session state is disabled by default in MVC and is generally not recommended unless absolutely necessary.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM