How long does a session[] retain data?

Pomster picture Pomster · Oct 29, 2012 · Viewed 11.2k times · Source

I am trying to use a session but when i need the value back its null?

My website starts off with a login where i put the user name into a Session.

Session["userName"] = login.UserName;

Then the website is redirected to a new page.

return RedirectToAction("Choice", new { token = token });

after witch i use a link to move to my next page.

@Html.ActionLink("Download", "Download", new {token = Model.Token})

Where i direct my code to a action result in the Home controller, the same controller i have my login function.

@Html.ActionLink("Download", "DownloadFile", new { fileid = item.Key, token = Model.Token, platform = "windows", filename = item.Value }, new {@class = "DownloadLink" } )

Where i try call up my session value again.

formMobiApi.GetFile(token, fileid, platform, filename, Session["userName"].ToString(), tasks, taskId, spreadSheetStatus);

Are any of these actions doing anything to make my session value null?

Can i use a session like this?

Answer

Paul Aldred-Bann picture Paul Aldred-Bann · Oct 29, 2012

If you are not manually setting your session state in web.config then the defaults you should have are in-process (sessions are stored in the RAM of the web server) and timeout is 20 minutes - see here for more information on session states.

You can manually set your states in your web.config file with the following:

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

Now, onto your actual issue. I'm not exactly sure why your session isn't persisting and I can't feasibly find out as I don't have a copy of your code to debug. At a guess I'd say your HttpContext is different from when you initialized the session, to when you're requesting it and so your context key is different. Try changing

Session["userName"].ToString();

to

HttpContext.Current.Session["userName"].ToString();

This looks a little odd at first glance, as you're effectively doing the EXACT same thing. The difference comes down to if the current object doesn't have access to the HttpContext you need to explicitly define which context to read from.

Having taken another look at the code you've provided, there's nothing out of the ordinary - this should work. I really am starting to believe this is an environment / configuration issue. If you're using Form Authentication then check your timeout in your web.config file. Also, if you're hosting in IIS (and not Visual Studio's web server - although you should check this too!) try deleting your application pool and recreating it.