How to handle session data in ASP.NET MVC
12,804
Solution 1
Not strictly related to the question itself, but more as a way of keeping controllers (reasonably) strongly typed and clean, I would also recommend a Session facade like class which wraps any session information in it, so that you read and write it in a nice way.
Example:
public static class SessionFacade
{
public static string CurrentLanguage
{
get
{
//Simply returns, but you could check for a null
//and initialise it with a default value accordingly...
return HttpContext.Current.Session["current_language"].ToString();
}
set
{
HttpContext.Current.Session["current_language"] = value;
}
}
}
Usage:
public ActionResultChangelangue(FormCollection form)
{
SessionFacade.CurrentLanguage = form["languageid"];
return View();
}
Solution 2
It should work, but is not a recommended strategy. Maybe session state is turned off in IIS or ASP.NET? See this answer and its comments.
Author by
Tom Maeckelberghe
Updated on June 11, 2022Comments
-
Tom Maeckelberghe almost 2 years
Let's say I want to store a variable called
language_id
in the session. I thought I might be able to do something like the following:public class CountryController : Controller { [WebMethod(EnableSession = true)] [AcceptVerbs(HttpVerbs.Post)] public ActionResultChangelangue(FormCollection form) { Session["current_language"] = form["languageid"]; return View(); } }
But when I check the session it's always null. How come? Where can I find some information about handling session in ASP.NET MVC?