Jacob Saylor
Jacob Saylor

Reputation: 2381

Session values returning null

I am running an ASP MVC site locally (.Net 4.5) and am experincing an issue when trying to retrieve a value from session. I am calling the code from a static helper class similar to the following:

Helpers.cs

public static void SetSessionValue(string key, object value)
{       
    HttpContext.Current.Session[key] = value;
}

public static object GetSessionValue(string key)
{   
    return HttpContext.Current.Session[key];
}

AjaxController.cs

public ActionResult SetUserName(string username)
{
    Helpers.SetSessionValue("username", username);
}

public ActionResult GetUserName()
{
    var username = Helpers.GetSessionValue("username"); 
    return Json(new { valid = true, username });
}

The username above is an example, but I have multiple cases of this happening, and each time the value for the key is null, but the key persists. I further went on and added the following to SetSessionValue to test:

public static void SetSessionValue(string key, object value)
{       
    HttpContext.Current.Session[key] = value;
    var test = HttpContext.Current.Session[key];
}

The variable test would be populated with the value. I double checked all the variable names. The keys still exist in the collection, but the values disappear.

Attempted Solutions

Solution 1 - HttpContext.Current.Session null item

I set the following in my web config, no luck

<sessionState mode="InProc" timeout="20" />

Solution 2 - HttpContext.Current.Session is null when routing requests

I set the following in my web config, no luck

<remove name="Session" />
<add name="Session" type="System.Web.SessionState.SessionStateModule"/>

Other Items I've tried

Upvotes: 2

Views: 7560

Answers (2)

Jacob Saylor
Jacob Saylor

Reputation: 2381

Found the issue... and feel like an idiot. Even though I went and closed all the instances in IIS Express and my running Services, there was another instance of the project being ran somewhere, thus confusing my session items.

To make sure I had everything up to date, I went in and modified the port number (Right click Project -> Properties)

enter image description here

After doing so, everything worked as expected. This might be a very unique case, but wanted to post just in case someone might run into a similar situation.

Upvotes: 3

akardon
akardon

Reputation: 45966

You've almost checked everything, just check with cookieless mode ,see what comes up, I guess there is something wrong with your cookie stuff :

<sessionState mode="InProc" cookieless="true" />

Upvotes: 0

Related Questions