weejing weejing - 2 months ago 20
ASP.NET (C#) Question

Wierd asp.net session fix

I recently encountered a weird issue with asp.net session which actually occurred in the sample code below.

Code that created a session (Login.aspx.cs)

public partial class Login : System.Web.UI.Page
{
protected async void btnLogin_Click(object sender, EventArgs e)
{

await request_login();
if (canLogin == true)
{
Response.Redirect("Dashboard.aspx");
}
}

private async Task request_login()
{
// call web service with httpClient
Session["key"] = "session object to be stored";
}
}


Code that calls the session (Dashboard.aspx.cs)

public partial class Dashboard : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
String sessionDetails = Session["key"] as String;
}
}


When I ran this piece of code, I got an empty string from the
Session["Key"]
. I managed to solve this issue with a weird fix by adding a dummy session in my home.aspx file (which is essentially the default page of the website).

Home.aspx.cs

public partial class Home : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
//wierd fix that allows session access
Session["home"] = "fromHome";
}
}


After adding
Session["home"]
, my
Session["key"]
was able to work perfectly. Why did this occur? Shouldn't
Session["key"]
be able to work perfectly without needing to add
Session["home"]
in home.aspx.cs?

Answer

try this :

public partial class Login : System.Web.UI.Page
{
    protected async void btnLogin_Click(object sender, EventArgs e)
        {

            await request_login();
            if (canLogin == true)
            {
                Response.Redirect("Dashboard.aspx",false);
            }
         }

   private async Task request_login()
        {
            // call web service with httpClient
               Session["key"] = "session object to be stored";
        }
}

So this will not abort the thread.

If you want to know the exact reason of why this happen visit this : http://weblogs.asp.net/bleroy/Don_2700_t-redirect-after-setting-a-Session-variable-_2800_or-do-it-right_2900_