Session Variables Is Null after Redirecting to a New Page

Josiane Ferice picture Josiane Ferice · Mar 27, 2014 · Viewed 10.8k times · Source

MVS 2012 SQL Server 2008 R2

I have an object that is being store in a session using a session wrapper. During login, I initialize the object and set the session appropriately. After authenticating the user, I redirect the user to the user index page. The user is redirected to the index page, but the session variable is not null. I am not sure why that is happening. Here is a sample code of what I am doing.

Here is my web config setting. If I comment out this web config section and run the application again, it worked fine.

<sessionState mode="SQLServer" allowCustomSqlDatabase="true" timeout="60" cookieless="false" sqlConnectionString="Data Source=(****);Initial Catalog=data1;User ID=****;Password=****;Integrated Security=True" />

This is the object that is wrapped in the session

 public class CurrentRequest
 {
   public int UserId { get; set; }
   public string Role { get; set; }
 }

here is the session wrapper

 public static CurrentRequest currentRequest
 {
   get
   {
     if (HttpContext.Current.Session["request"] != null)
     {
       return (CurrentRequest)HttpContext.Current.Session["request"];
     }
     else
     {
       return null;
     }
   }
   set
   {
     HttpContext.Current.Session["request"] = value;
   }
 }

Here I am checking the role and redirect the user to the appropriate page

CurrentRequest currentRequest = new CurrentRequest();
SessionWrapper.currentRequest = currentRequest;
int userId = login.GetUserId(model.UserName, true);
SessionWrapper.currentRequest.UserName = model.UserName;
string[] roles = Roles.GetRolesForUser(model.UserName);
if (roles.Count() > 0)
{
  string aRole = roles[0];
  switch (aRole)
  {
    case "Admin":
      SessionWrapper.currentRequest.Role = aRole;
      SessionWrapper.currentRequest.UserId = userId; 
.
.

the sessions variables above are set properly and I am redirecting the user to the Users' Index page

return RedirectToAction("Index", "Users");
                    case "User":

On the Users Controller, I am checking to see if this user is an admin or not, but the session variable SessionWrapper.currentRequest is null

if (SessionWrapper.currentRequest.Role == "Admin")
{
  users = db.UserRepository.GetAll();
}

What I am doing wrong here?

Answer

Josiane Ferice picture Josiane Ferice · Mar 28, 2014

I found the issue. I did not have Session_Start and a Session_End methods in my global.asax file. I added these two methods signature, and it was no longer an issue.

protected void Session_Start(object sender, EventArgs e)
{

}
protected void Session_End(object sender, EventArgs e)
{

}