Tales from the Evil Empire

Bertrand Le Roy's blog

News

Ads Via DevMavens

ASP.NET AJAX UpdatePanel Control: Add Ajax interactivity to your ASP.NET 2.0 web pages


follow bleroy at http://twitter.com

Bertrand Le Roy




Add to Technorati Favorites

Blogs I read

My other stuff

Don't redirect after setting a Session variable (or do it right)

A problem I see over and over again on the ASP.NET forums is the following:
In a login page, if the user and password have been validated, the page developer wants to redirect to the default page. To do this, he writes the following code:
Session["Login"] = true;
Response.Redirect("~/default.aspx");
Well, this doesn't work. Can you see why? Yes, it's because of the way Redirect and session variables work.
When you create a new session (that is, the first time you write to a Session variable), ASP.NET sets a volatile cookie on the client that contains the session token. On all subsequent requests, and as long as the server session and the client cookie have not expired, ASP.NET can look at this cookie and find the right session.
Now, what Redirect does is to send a special header to the client so that it asks the server for a different page than the one it was waiting for. Server-side, after sending this header, Redirect ends the response. This is a very violent thing to do. Response.End actually stops the execution of the page wherever it is using a ThreadAbortException.
What happens really here is that the session token gets lost in the battle.
There are a few things you can do to solve this problem.
First, in the case of the forms authentication, we already provide a special redirect method: FormsAuthentication.RedirectFromLoginPage. This method is great because, well, it works, and also because it will return the user to the page he was asking for in the first place, and not always default. This means that the user can bookmark protected pages on the site, among other things.
Another thing you can do is use the overloaded version of Redirect:
Response.Redirect("~/default.aspx", false);
This does not abort the thread and thus conserve the session token. Actually, this overload is used internally by RedirectFromLoginPage. As a matter of facts, I would advise to always use this overloaded version over the other just to avoid the nasty effects of the exception. The non-overloaded version is actually here to stay syntactically compatible with classic ASP.
UPDATE: session loss problems can also result from a misconfigured application pool. For example, if the application pool your site is running is configured as a web farm or a web garden (by setting the maximum number of worker processes to more than one), and if you're not using the session service or SQL sessions, incoming requests will unpredictably go to one of the worker processes, and if it's not the one the session was created on, it's lost.
The solutions to this problem is either not to use a web garden if you don't need the performance boost, or use one of the out of process session providers.
More on web gardens: http://technet2.microsoft.com/WindowsServer/en/library/f38ee1ff-bdd5-4a5d-bef6-b037c77b44101033.mspx?mfr=true
How to configure IIS worker process isolation mode: http://www.microsoft.com/technet/prodtechnol/WindowsServer2003/Library/IIS/26d8cee3-ec31-4148-afab-b6e089a0300b.mspx?mfr=true
Thanks to Frédéric Gareau for pointing that out.
UPDATE 2: Another thing that can cause similar problems is if your server has a name that contains underscores. Underscores are not allowed in host names by RFC 952 and may interfere with the ability to set cookies and thus to persist sessions.

Comments

TrackBack said:

# August 4, 2004 2:45 AM

Siva Mateti said:

Why not use Server.Transfer instead of Response.Redirect especially if both pages are aspx? How can I avoid ThreadAbortException for Server.Transfer?
# August 4, 2004 9:22 AM

Bertrand Le Roy said:

Excellent question.
Server.Transfer will not get the right URL in the address line of the user's browser. If that's acceptable, you can use Transfer, and you save one client/server roundtrip.
Now, Transfer also has a Response.End (and hence a ThreadAbortException), but the code inside Transfer is really just two lines:
Execute(path, null, preserveForm);
Response.End();

So you see that to avoid the exception for Transfer, you should just use Execute instead.
Of course, if you do that, you still need to suppress the output from the first page because both pages will output to the same response (you don't need to do that with Redirect because you have two separate requests in this case, and thus two different responses, the first one being thrown away). This can be done by clearing the response before calling Execute or doing some funny stuff with the writer parameter of Execute. Many strange scenarios here ;)
# August 4, 2004 1:19 PM

TrackBack said:

# August 5, 2004 3:09 AM

Siva Mateti said:

# August 5, 2004 8:55 AM

g said:

I tried to used the

Response.Redirect("~/default.aspx", false);

on a normal ASP page and get "Wrong number of arguments or invalid property assignment"

Is there a solution for the same problem in a non- .net environment?
# August 19, 2004 10:53 AM

Bertrand Le Roy said:

g: This version of Redirect only exists in ASP.NET, not in classic ASP. There is no such thing as an exception in classic ASP, so you actually don't have this problem at all as far as I know, so no need to solve it ;) But I may be wrong. It's been such a long time since I've done any classic ASP at all.
# August 19, 2004 2:13 PM

Disappointed said:

Tried Response.Redirect("~/blah.aspx", false) ... I still have the same issue. I've seen a lot of "I have teh SOLUTIONZ!!!111" articles on this issue, but have yet to see anyone with a real fix. :(
# August 19, 2006 12:18 PM

Carol said:

> Response.Redirect("default.aspx", true); > Response.Redirect("default.aspx", false); > Response.Redirect("default.aspx"); Should I be losing Session() variables 'sometimes' or 'always' when I redirect? I tried all 3 of the above in a small bit of test-code... and didn't seem to lose any vars, ever. But my production code (about 500 lines) does lose session() vars... but only at randoms times. I can't seem to "make" it happen (with redirect... or without.) Help!
# August 21, 2006 8:42 PM

Bertrand Le Roy said:

Disappointed: drop me e-mail using the "e-mail" page of this blog with a simple repro (avoid dependancies if you can, try to make it as simple as possible) and I'll try to find what's wrong.

Carol: you will only lose session variables if the session does not yet exist when you do the redirect. What doesn't get set here is not the session variable in itself, it's the cookie that identifies the session.

# August 22, 2006 1:59 PM

Carol said:

> you will only lose session variables if the > session does not yet exist You are going to have to explain that 1. How can I lose something... that doesn't exist? Can you give an example in asp.net v1.1? I need code that I can run... and watch my session vars disappear *EVERY* time. (Not the current "randomly" method... that I can't seem to track down or prevent.) Thanks.
# August 26, 2006 2:37 AM

Bertrand Le Roy said:

Carol: if the session does not exist yet, *then* you set a session variable and redirect right after, the session variable you just set will not persist.

(this, by the way, is the example in the post)

If the session already existed before this request, the session cookie is already set and everything should work fine.

# August 28, 2006 12:42 AM

Ludmal's Blog said:

Really good post about Creating Session variables and Redirecting the page.http://weblogs.asp.net/bleroy/archive/2004/08/03/207486.asp...

# September 15, 2006 12:40 PM

Troubled said:

Hello Bertrand Le Roy, I'm using : Session["MemberNo"] = 5; Response.Redirect("~/ViewMember.aspx", false); and i'm still losing the sesion value once steping over Response.Redirect. What might be the reason causing this behavior.
# September 23, 2006 4:14 PM

Bertrand Le Roy said:

Troubled: send me mail at bleroy at microsoft com with code to reproduce the problem and I'll have a look.

# September 24, 2006 12:56 AM

Matt G said:

Since I came across this post I was curious if a problem I'm have getting Response.Redirect working with an UpdatePanel is related to this issue. According to what I've seen this issue was resolved a while back, but response.redirect does not seem to work for me.
# October 11, 2006 11:34 AM

Bertrand Le Roy said:

Matt: send me a simple repro of your problem at bleroy (at microsoft). I'll have a look.

# October 11, 2006 12:41 PM

Zenute Marins said:

This is very confusing! I have two web applications with Atlas and in the first one I can save and retrieve Session variables after redirecting like in (Response.Redirect("Clientes.aspx")). The second application using the same code as described above fails with a null exception when I try to retrieve any Session variable prevously saved. i'm going nuts here!
# October 23, 2006 10:26 AM

Bertrand Le Roy said:

Zenute: one thing to look for is wether the session already exists before you do the redirect but if in doubt, use the overload as explained in the post.

# October 23, 2006 3:54 PM

kleolb02 said:

Maybe you have the same problem I had. Response.Redirect doesn't work after a Postback before OnInit. Another possible error could be a Session- Timeout, the solution would be to set the timeout in the web.config- file.

hope this helps..

# November 23, 2006 4:08 PM

ASPCoder said:

I have a strange but a problem similar to one reported here. I have an ASP.NET application in which after loggin in, I set a session variable and then do a response.redirect. So far everything has worked well and I am able to access this variable from all other pages. But recently, the users noticed a problem. In a particular page, after showing a message, we do a <meta http-equiv=refresh content=3;url=someurl.aspx>. Which is refresh the page and redirect to another url. In the someurl.aspx, we check for session variable and some inexplicable reason, it is getting lost and the users are redirected to the login page. Appreciate any ideas.

thanks

# December 1, 2006 12:06 PM

Sandeepan Kundu said:

i am using ATLAS with a timer which updates the grid every 2 to 3 seconds.....  i was facing the same problem ...

i am doing response.redirect and based on a session variable i fill data according to user....

if user's credentials are not avaiable from session i used to redirect to login page... as only on session expiry the information became void....

i am making postback using the ATLAS's timer.

now on session timeout the timer tick event(i.e.) post back i am refreshing the session's timeout which is one way solving my problem.....

if ne1 can get with a better solution... please revert back at sandeepan.kundu@tv18online.com

Thanks

Sandeepan

# December 2, 2006 6:05 AM

craig said:

I have a site I am building and I need to redirect, transfer, or forward to another site.  I don't want to have the query string parameters visible to the user, so I have a link that goes to a page that loads the session with the parameters and redirects to the other site.  See code below:

           Session["Service"] = DataLayer.getProperGroupName((string)dr["TICKET_GROUP"]);

           Session["Requester"] = dr["NAME"];

           Session["Telephone"] = dr["PHONE"];

           Session["CallReason"] = dr["DESCRIPTION"];

           Session["RequestDate"] = dr["TICKET_CREATE_DATE"];

           Session["ID"] = id;

           Response.Redirect(DataLayer.getSurveyURL());

I am new to .Net, so what are my other options.  This site sends emails to customers with a link to a survey and I have a page with links for a person at my company to do phone surveys using the same link.  I would like to hide my data, to keep the user from trying to muck with it.

# December 19, 2006 8:27 PM

Bertrand Le Roy said:

Craig: yes, that sounds ok. An alternative that avoids session altogether is to use cross-page posting. You can set the postback url of your submit button for example, and the target page can then get an instance of the previous page and access all its state (including textbox values, etc.) using the PreviousPage property (it may be necessary to cast it to the right type to avoid having to do too many FindControls).

# December 19, 2006 8:38 PM

craig said:

It seems to have a problem though.  The other site is not getting the parameters.  Does Redirect only work if it is on the same server?  My final deployment may put both sites on the same server, but I can't guarantee that yet.

Any ideas?

Thanks you so much!

# December 19, 2006 8:44 PM

Bertrand Le Roy said:

Ah, no, it's not the redirect that doesn't work here, it's session. If it's a different server, it's a different session (unless it's a web farm).

# December 19, 2006 8:49 PM

Travis Cable said:

I am having this exact problem with Classic ASP. Any ideas to use something other than Response.Redirect?

# January 5, 2007 3:55 AM

Bertrand Le Roy said:

Classic ASP? Wow.

I suppose you could set the redirection headers and status, which would simulate what Redirect is doing, only without the thread abort.

# January 5, 2007 2:07 PM

kurtsune said:

This works:

page1.cs

protected void Page_Load(object sender, EventArgs e)

{

throw new Exception("hhhhhhhhh");

}

void Application_Error(object sender, EventArgs e)

{

Exception ex = Server.GetLastError();

HttpContext.Current.Session["Error"] = ex.Message;

Server.ClearError();  

Response.Redirect("error.aspx");

}

in error.cs

protected void Page_Load(object sender, EventArgs e)

{

if (Session["Error"] != null)

{

Response.Write(Session["Error"].ToString());

Session.Remove("Error");

}

}

This does not work:

page1.cs

protected btResponseRedirectToNonExistantPage(object sender, EventArgs e)

{

Response.Redirect("NonExistantPage.aspx", False);

}

void Application_Error(object sender, EventArgs e)

{

Exception ex = Server.GetLastError();

HttpContext.Current.Session["Error"] = ex.Message;

Server.ClearError();  

Response.Redirect("error.aspx");

}

in error.cs

protected void Page_Load(object sender, EventArgs e)

{

if (Session["Error"] != null)

{

Response.Write(Session["Error"].ToString());

Session.Remove("Error");

}

}

==> Object reference not set to an instance of an object.

# January 8, 2007 3:05 AM

Tony said:

I have the same problem for Redirect methid. For me i have 2 server that have the same code(just set Session and Redirect after that), then one server(Windows XP Professional) is not lost the Session but another server (Window 2000 Server SP4) is lost the Session. I'm so confuse.

# January 9, 2007 4:25 AM

Bertrand Le Roy said:

Tony: it's hard to tell exactly what's happening in your case. You should contact support.

# January 9, 2007 1:45 PM

Bhaskar Jayakrishnan said:

One of the observations when using Response.Redirect(<url>, false) is that the page sent back to the browser contains 2 complete HTML blocks - 1 of the redirect (~150 bytes), and the other of the original page itself.

Adding:        

protected override void Render(HtmlTextWriter writer)

       {

           if (!Response.IsRequestBeingRedirected)

               base.Render(writer);

       }

to the page's or to the master page's code behind, resolves the issue.

Redirection being one of the very common cases, this appears to be a not-so-elegant way of doing things.

Is there a better solution ?

# January 28, 2007 12:11 AM

Bertrand Le Roy said:

Bhaskar: good point. You could also set-up a response filter that swallows all new output.

# January 29, 2007 1:24 PM

Yes, You can redirect.................... said:

Dear All,

if you are using ATLAS you can face the problem of session after redirecting the page. session's value gets null. You can solve this problem by using follow instructions.

1- Just maintain another session like a test session on the form load of the page from where you are redirecting the page.

for example:

---------------------------------------

page_load event()

{

if(!Page.IsPostback)

{

Session["TempSession"]="";

}

---------------------------------------

After doing this you can make use of sessions easily.

but remember on form load only because this is not included in atlas controls.

}

if any doubt you can catch me at 'dear.saxena@orkut.com' or 'saxena-saurabh@hotmail.com'

Thanks & Regards

Saurabh Saxena

# February 12, 2007 4:48 AM

EB said:

I was having this problem in ASP.NET and I did two things to fix it (just to be safe):

1) used the second "false" parameter in Response.Redirect

2) since as you explained, the problem is only if the session hasn't been started on a page prior to the one that does the redirect, I set a dummy session variable when the user first arrives at the login page, BEFORE they've submitted the form.

Either one or both of these seems to have done the trick.  Thanks Bertrand!

# March 5, 2007 11:00 AM

boa sovann said:

i am also having such this problem in my web application and trying to find the solutions. but i really get strange! when try to login with the correct username and password, the session variable always null but if i enter the wrong username or password at the first time and try to enter the correct username and password again, it works correctly. so why it is happend?

# March 12, 2007 11:44 PM

Bertrand Le Roy said:

Boa: if login fails, there is no redirection, so the session cookie gets set correctly. This is expected. Follow the indications in this post and you should be fine.

# March 13, 2007 1:55 PM

Rem said:

Hi Betrand,

Searching for an answer this weird is hard, even with google on our side. I'm not sure if my problem is along the same line, however, this is what's happening:

I store some login information in my session as well. Now for some reason -this behaviour started all of a sudden with a minor update not touching any of the login stuff- if I refresh a lot, and print the session variables, it SOMETIMES takes the data from a different session.

Any ideas where this might come from, or better yet, how to prevent it?

Thanks in advance,

Rem.

# March 26, 2007 11:19 AM

Bertrand Le Roy said:

Rem: it's hard to say but I'd bet for a caching issue. If the project is under source control and you know when this started to happen, try to determine which changes are likely to have done that and look in particular for changes in the caching policies of those pages.

# March 26, 2007 1:33 PM

Rem said:

Bertrand (correctly this time): The changes were very small and I can't think of anything that has any correlation to caching or sessions.

I haven't been able to find anybody describing this behaviour in my searches. Personally, I'm starting to think it's beyond the application, but that's something wrong with IIS. Sessionstate is set InProc for this.

If you would happen to know a place where I could find people who have or had this problem, that would be appreciated!

Thanks again,

Rem.

# March 27, 2007 5:15 AM

Bertrand Le Roy said:

Rem: if it was caused at the same time as a code change, I'd try to rule that out first. Can you revert those changes and see if it still reproes?

If all else fails, I'd advise you to contact support.

# March 27, 2007 1:58 PM

Rem said:

We tried that just now and the old code doesn't show the behaviour, so it must be in the code somewhere. 5 of us have been staring ourselves blind on it with no result.

Wish I could find something that may give a suggestion what causes sessions to swap. Only thing I've found is multiple worker processes, but that's not the case here.

Errors are fine, we can fix those. No errors and weird behaviour, that's a whole different story. Perhaps I should have my wife (who doesn't code) look at it...

# March 28, 2007 4:36 AM

Sebastian said:

I can't seem to avoid this behaviour by using:

protected void btn_Submit_Click(object sender, EventArgs e)

   {

       Session["Branchevereniging"]    = ddl_Branche.Text;

       //SNIP

       Response.Redirect("Offerte.aspx", false);

   }

I'm fairly new to (asp).NET so that might have something to do with it, anyway I could solve this?

# May 10, 2007 11:17 AM

Bertrand Le Roy said:

Sebastian: I wasn't able to reproduce a problem with that code. Feel free to send me your repro.

# May 10, 2007 7:06 PM

drashty said:

i do have problem of loosing session but its not after or before redirecting.What i am doing is set sessions when any user logs in and after that in change password page i ask for username password,new password and confirm password and i have put client side validation of required field all fields and compare validator for new and confirm password after submitting form for the first time if a user with given username and password doesnt exist then if gives username or password is invalid but when u retype everything and submit i found that all sessions are cleared.What could be the possible reason.Help me.Can revert back on drashty2004@yahoo.com
# June 11, 2007 3:49 AM

Bill Wolfe said:

I did the same thing that EB did from March 5, 2007 and it worked great.

# July 10, 2007 12:22 PM

Naveen said:

Hi,

I'm Using the following code..

Session("Test") = Value

Response.redirect("PageName.aspx",false)

The redirection and loading of the second pae fgoes on fine but the Session Vatiable value is lost before the timeout.

I'm using global.asax file to set the Session .Timeout to 240 and alternatively specifying the same in web.config.

Would like to know what's wrong....

Thanks and Regards,

Naveen

P.S : I'm using Master Page in the application and checking the Session values in page load.

# July 16, 2007 7:43 AM

Bertrand Le Roy said:

Naveen: you must be doing something else than that, because just that code you're showing works fine. You can send me your repro at bleroy at microsoft dot com.

# July 16, 2007 1:55 PM

Prasad said:

hi  bleroy,

       thats a wonderful article... its still not working...the code is given below

Session.Add("registrationinformation", userinfo)          Response.Redirect("0.0.0.0/abac.aspx", False)

the above code runs in a iframe tag and its not working ...as you have said the session data is being lost even though i said in the same way.Can u suggest me how can i resolve it?

it worked fine in local address but on production server it fails when i give ipaddress for redirecting to the next page in registration?

thanks for your support

# August 6, 2007 10:49 AM

Bertrand Le Roy said:

Prasad: what's this 0.0.0.0 in your code? Redirecting with a fully-qualified address is probably the problem here. If it's identified by the browser as the same domain, you only needed a relative address and if it's not, it's rightfully not serving the same cookies. In other words I would expect this to fail.

# August 7, 2007 2:36 AM

Prasad said:

hi bertrand

     thanks for the reply,

-----> for security reasons i have changed the ip address and the page name else they are fine.All pages are in the same domain and in the same folder .

-------> Here i am loading full application in an iframe .do you think that can cause issues because without iframe everything works just fine?  

---->In FIREFOX it works even inside iframe & not in IE .

But when i enable cookies from all sites in my IE then my application works again.(my application is currently not certified so is IE may be prohibiting something ????)Can u make me clear about this strange behavior?

----->Can u please suggest me the solution to redirect page in a iframe when i use cookies like in login or registration .

---> i am using asp.net1.1

thanks in advance..

# August 7, 2007 9:43 AM

Bertrand Le Roy said:

Prasad: again, I think it's because you're fully-qualifying the domain. Can you try with relative addresses instead of always specifying the domain as part of the url?

# August 7, 2007 5:55 PM

Prasad said:

i tried intially using relative addresess it failed so tried the below it works fine

Server.Transfer("~/default.aspx");

but once i am logged on when i try again to click on a link made from anchor tag with link like "userdata.aspx" then i lose session data and get redirected to the login  page due to loss of session data due to a bug in IE

"Session variables are lost if you use FRAMESET in Internet Explorer 6" and link is shown below

support.microsoft.com/.../en-us

so i am planning to create privacy policy for my website hoping  then my application works fine .

thanks for help once again..

# August 8, 2007 9:04 AM

Bertrand Le Roy said:

Prasad: that's what I meant. Your code above seemed to imply that you had used the whole absolute thing with protocol, domain name, etc. This KB article seems to explain it, yes.

# August 8, 2007 3:13 PM

George said:

Any reason why this would work on one IIS server, but not work when moved to a different IIS server?

I'm using iframes and after a login I set a session variable and then refresh the page using Response.Redirect("~/Default.aspx", False)

This works ok on the first server, but when I tried to move the web site to another server, the login is unsuccessful (it seems that it's not setting the session variable or the session variable is being lost after redirect).  Is there an IIS setting somewhere that might control this?

Thanks

# August 21, 2007 3:50 PM

Bertrand Le Roy said:

George: there's probably a difference in config between the two. Are these the same versions of IIS, both fully updated?

# August 21, 2007 4:20 PM

George said:

Same versions of IIS (5.1) and I've looked at the settings in IIS Admin and they're the same. Is there any other way to refresh the page without creating a new session?

Using Server.Transfer("~/Default.aspx") refreshes the Default.aspx page and recognizes that the session variable has been set, however the iframe contained in Default.aspx (which may or may not have refreshed as well, I can't tell) doesn't recognize that the session variable has been set.

Thanks again.

# August 21, 2007 5:12 PM

Bertrand Le Roy said:

What about web.config? Can you try to reproduce the problem without the iframe?

# August 21, 2007 6:30 PM

George said:

web.config is equivalent across the two machines. and yes, without the iframe, the problem still exists on the one machine.

something i forgot to mention is that when viewed in firefox, the site works from both machines. it's only when viewed using IE that the site doesn't work when served from one of the machines.

this article (support.microsoft.com/.../en-us) lead me to believe it was some sort of IE security setting, but I tried the resolutions listed in the article and was unsuccessful.

# August 22, 2007 10:49 AM

George said:

Hate to bug you again but I just realized something about the two servers that might be important. The one that works is on a different domain than the one that doesn't work. Could there be some sort of group policy being applied on one of the domains that is setting security on IE that interferes with sessions/cookies?

# August 22, 2007 11:57 AM

Bertrand Le Roy said:

George: At this point I would contact support. I'm sorry I don't have any better insight for the moment.

# August 22, 2007 2:50 PM

George said:

Finally got it to work.

First I had to add this line to the web.config file right under the <system.web> tag:

<sessionState cookieless="true" timeout="20"></sessionState>

Then I changed my Response.Redirect calls to this:

Page.Response.Redirect(Page.Request.Url.AbsolutePath(), True)

Maybe someone out there has the same problem and can try this workaround to solve it.

# August 28, 2007 11:22 AM

Nick said:

I have tried everything with this problem - still no good. It really seems to be to do with IE and cookies - which is frustrating. Have a look at my post in ASP.NET forums - lots of detail on my problem.

forums.asp.net/.../1931020.aspx

I'd love some help...

thanks,

Nick

# September 27, 2007 11:20 PM

Max said:

I have the same problem with simple ASP, but I solved with a strange and unexplicable solution: I simply call the sessionId on top of page, with no precise function:

i simply write

SessionIdNumber=Session.SessionId

and all the following session values are not lost

?!?

# October 4, 2007 12:29 PM

HG said:

Thanks Bertrand for your article, but in my case the fix simply doesn't work. I've tried to call Redirect with false, set a dummy session variable and nothing. I'm really at a loss here.

I have a Login page, from which the user goes to a main admin page (default.aspx), which has 2 buttons, one that opens an Orders page, the other one an Artists page.

Here is some of my code:

In Login:

   protected void Page_Load(object sender, EventArgs e) {

       if (!IsPostBack) {

           string previousPageCode = Request.QueryString["p"];

           switch (previousPageCode) {

               case "o":

                   adminLogin.DestinationPageUrl = "~/admin/Orders.aspx";

                   break;

               case "a":

                   adminLogin.DestinationPageUrl = "~/admin/Artists.aspx";

                   break;

               default:

                   adminLogin.DestinationPageUrl = "~/admin/Default.aspx";

                   break;

           }

       }

   }

   protected void adminLogin_Authenticate(object sender, AuthenticateEventArgs e) {

       Admin adminUser = new Admin(adminLogin.UserName, adminLogin.Password);

       if (adminUser.IsAuthenticated) {

           e.Authenticated = true;

           Session["theAdminUser"] = adminUser;

       }

   }

In default.aspx:

   protected void Page_Load(object sender, EventArgs e) {

       Admin adminUser = Session["theAdminUser"] as Admin;

       if (adminUser == null || !adminUser.IsAuthenticated) {

           Response.Redirect("Login.aspx", false);

       }

   }

   protected void btnOrders_Click(object sender, EventArgs e) {

       Response.Redirect("Orders.aspx", false);

   }

   protected void btnArtists_Click(object sender, EventArgs e) {

       Response.Redirect("Artists.aspx", false);

   }

   protected void btnLogOut_Click(object sender, EventArgs e) {

       Session.Remove("theAdminUser");

       Response.Redirect("Login.aspx");

   }

And in Artists.aspx (Orders.aspx is similar):

   protected void Page_Load(object sender, EventArgs e) {

       Admin adminUser = Session["theAdminUser"] as Admin;

       if (adminUser == null || !adminUser.IsAuthenticated) {

           Response.Redirect("Login.aspx?p=a", false);

       }

       lblErrMsg.Text = "";

       if (!IsPostBack) {

           //...

       }

   }

   protected void btnAdmin_Click(object sender, EventArgs e) {

       Response.Redirect("Default.aspx", false);

   }

   protected void btnLogOut_Click(object sender, EventArgs e) {

       Session.Remove("theAdminUser");

       Response.Redirect("Login.aspx");

   }

# October 11, 2007 11:36 PM

Bertrand Le Roy said:

HG, we should take that offline. Please contact me through the contact form of this blog.

My question would be why you don't use Forms authentication instead of rolling out your own that has hard-coded pages and that is unlikely to be easily maintanable in the long run?

# October 12, 2007 2:21 PM

Robert said:

Please use Session.Add(name as string, value as string)

Make sure you don't clear any sessions and strictly declare your variables to session if you are doing so.

Hope that helps!

# October 23, 2007 4:53 PM

Jral said:

What I would like to know is:

Is this only a problem if adding something to Session for the first time?

That is, if i simply update a variable in Session and perform a Redirect on the next line, is my application still open to potential problems????

# October 25, 2007 10:48 AM

PriyaS said:

Thanks for the informative Redirect/Session related discussion going on.

I have a similar issue (not exactly). I'm working on migrating a classic ASP shopping cart app to .NET. On one particular condition we need to redirect the user to the old ASP site to grab the details. The redirect logic works flawlessly on all pages except the home/default page. I mean the logic works on my local host but does not work when moved to a Server. Any clue as to what I may be doing incorrectly?

Thanks in advance.

# December 7, 2007 1:14 PM

Bertrand Le Roy said:

Priya: if you provide more details on how it fails, we might be able to tell what's going on. Feel free to send me mail through the contact form.

# December 7, 2007 1:41 PM

Will said:

Your my hero, thanks for writing this.

# December 13, 2007 8:58 PM

Dimitris said:

I can't simulate this and never ever had such a problem. I don't think that it is that straight forward, since I see that other people as well (Carol) don't get that error!

I used to test it:

Session.Clear();

Session["Test"] = "test";

Response.Redirect("default.aspx", true);

The session is never lost

# February 27, 2008 9:59 AM

Matt said:

Dimitris- Clearing the Session is not the same as the Session never existing in the first place.  An appropriate test would be along the lines of:

Session.Abandon();

Session["Test"] = "test";

Response.Redirect("default.aspx", true);

I tested the above code as a button click handler on an otherwise empty web form called test.aspx, then on page load of default.aspx I set the Text property of a Label control to the value of Session["Test"], if Session["Test"] was not null.  With your code using Session.Clear() it worked fine (default.aspx displayed "test" in the label).  With my Session.Abandon() version it mimics the issue described in the article.

For what it's worth, when we experienced this problem after a deployment it turned out to be the server name containing an underscore as mentioned in Update 2.  Accessing that machine by the IP works fine (it's an internal application so the users just updated their favorites to point to the static IP instead of the hostname on the LAN).  That will have to do until our customer's IT department sees fit to change the hostname of the server.

Thanks again for the article Bertrand, saved me from pulling my hair out.

# March 12, 2008 3:43 PM

Oldschool said:

I'm not able to reproduce the "problem"

First time you load the page:

Session["dummyToKeepSessionAlive"] = "xD";

Second time you load the page:

Session["LoggedIn"] = true;

Response.Redirect("Loggedin.aspx");

Third time you load the page:

if(Session["LoggedIn"] == true)

NeverFailedMeOnce();

# March 20, 2008 6:04 PM

Joel Levi said:

I was alo facing the same issue with Redirection but Bertrand Le Roy's article solved it. Works fine now.

Thanks, very helpfull.

# April 3, 2008 1:56 AM

Matt said:

Response.Redirect("~/default.aspx");

...should be...

Response.Redirect("~/");

12 less keystrokes will a) prevent your URL from looking ugly/unprofessional, and b) when you upgrade your site to the next big thing and the file extensions change (remember going from asp to aspx?), the links that search engines spidered won't stop working.

# April 10, 2008 11:16 AM

Richard said:

Excellent article and the update section helped here with regard to maximum number of worker processes with a value above 1

# April 11, 2008 2:17 AM

James said:

I was lossing session data after clicking on a new page on a web site I was building only one of the pages out of about 25 was having this issue and it was always the same page.  As soon as I copied the page on to the IIS server on my computer the problem went away.  I think that something was going wrong on the server that visual web developer 2005 was running.

# April 18, 2008 4:12 AM

linukalex said:

hi, I am faceing mainly 2 problem with my web site.When i run my website in development server, almost everything works perfect except response.redirect().I have developed a shopping cart web site which uses a master page and lots of content pages.There is index page which also uses the master page.In my master page i wrote lots of codes to control the web site.For example i have used a datalist which has paging facility, for this i used a session to keep the table and the whenever some click events happens , i change the session values with new table.This works fine in development , i get all the changes also, but i published it i am not getting the changes when some click event fires, i am getting the first data which v assigned in the load event of the master page.Y it happenes like this, i mean locally it works fine but after publishing it shows only the data which is assigned in the load event of the page? Please help me out..

second problem is that when i click a control which is in the master page , i used the response.redirect to the index page with some querystring, i am getting a execption/error.but as i simply  give  catch execption without any other statement its not making a problem. Will it be reason for the above problem, as when a click event fires i used , response.redirect or server.transfer() with querystring to reload the index page , where it will make a check for the position (based on the querystring) & get values from db and assigns it to the session as a table....

This all works in the development fine ....

Please help me out as I am struggling bit hard on it.....

# May 24, 2008 2:32 AM

homey said:

Nice discussion.

I am simply trying to pass some variables from asp to aspx page. If I use session, they dissappear, if I use query string, they dissapear. I don't get it.

If I manually paste the url into the browser, everything is fine, so I know my aspx page is recieving the querystring. But, when I use the response.redirect from the asp page with the params in the query string, they dissapear somehow.

ex: response.redirect("/somepage.aspx?name=value")

Any ideas?

# May 28, 2008 9:35 AM

homey said:

Got it working. nevermind.

When I feel really adventurous I will try upgrading it to the more secure session method, but for now query string will have to work.

# May 28, 2008 10:02 AM

Bertrand Le Roy said:

@linukalex: difficult to say without seeing the code. Feel free to drop me e-mail through the contact form.

# May 28, 2008 8:41 PM

Brian S said:

Hi Bertrand

I have a similar problem with ASP pages.

I am setting a session variable:

 Session("locadd") = "1"

on a page "add.asp" which gathers certain location data from input.

Upon clicking the Submit button, the following code is run:

 TheForm.action = "add_res.asp"

 TheForm.submit

In the "add_res.asp" page, the Session("locadd") is empty.  It appears to be working on the production server but not the Dev or Staging server.

Any ideas?

# June 16, 2008 1:24 PM

Bertrand Le Roy said:

@Brian: I don't know much about how this works in classic ASP. You should probably contact support on this one.

# June 16, 2008 3:47 PM

BFuller said:

I have this problem in classic ASP on a site that had been running fine for a few years. One day it up and errors because the session variables are cleared on redirects for seemingly no reason. This makes me think a server update of some variety is to blame since some server updates were installed around that time.

# June 18, 2008 6:35 PM

Radha said:

After setting session varibales, I am redirecting page. Its working on local host but its not working on server.

# July 2, 2008 2:54 PM

Stif said:

Hi Bertrand

I have the following issue:

When a user visits my website for the first time and my sql server is down, I get an exception during the PreRequestHandlerExecute event (while making my connection to the database). I have a IHttpModule which adds an eventhandler for the application_error event. This eventhandler places some info on the session. In my web config I've enabled custom errors and specified a default redirect. The errorpage asp.net redirects to, gets the info from the session and displays it. But as you probably guessed, I'm losing the session info, because it's the first time the session is built. So you see, the problem is I'm not performing the redirect myself, but letting asp.net do the work. Would there be a way to overcome this problem (other than having to perform the redirect myself)?

Any help would be greatly appreciated

Grtz

Stif

# July 3, 2008 4:46 AM

Bertrand Le Roy said:

@Stif: if you've tried all the workarounds in the post and it still doesn't work, I would advise that you contact support.

# July 3, 2008 1:53 PM

Lou said:

Hi Bertrand, Please could you clarify something for me?

I am calling Response.Redirect from Application_PreRequestHandlerExecute within Global.asax.  My understanding is that as it is within Global.asax the HttpResponse.End method will not be called and the thread will not be aborted.  Would the first page be executed and sent back to the client, or would the client only receive the page to which it is being redirected (having earlier received the special header directing it to request the new page)?  This is critical as in the situation I am working with, the page originally requested is dependent on unavailable services and it is important that this code does not execute.

# July 9, 2008 8:41 AM

Bertrand Le Roy said:

@Lou: this should be easy to check by putting a breakpoint in the code you don't want to run. One thing I can tell you is that the client will never receive the first page: a redirect works by sending the browser a special header that instructs it to navigate to the new url instead of the old one. There is no contents in the first request, but that doesn't mean that the server code necessarily stops running.

# July 9, 2008 2:20 PM

Jim diGriz said:

Max - thank you for your comment! works great :)

# July 16, 2008 11:54 AM

Aneesh Abraham said:

Hi , Guys.

I had the above issue with my project and tried most of the solutions provided above.

In my project user has to upload his photo during account creation. So every time there will be some changes in the root directory.

As per the info provided here:

blogs.msdn.com/.../668412.aspx

, every change in directory structure , re starts the application and the sesion vanishes.

In order to solve this issue i used the "Profile" object in ASP.net 2.0 which stored the data in a seperate SQL file.

Hope this helps some one....

# July 18, 2008 7:37 AM

Bertrand Le Roy said:

@Aneesh: it seems like you already found the solution. Letting the user write into the root directory of your application was dangerous practice anyway, and couldn't have been done without opening up the ACL on the directoy. Storing in a different place (a database, a separate directory, profile etc.) is the right thing to do.

# July 18, 2008 1:57 PM

Troy said:

Dear Bertrand,

I lost the session vaiables. Why? Below my code:

Thx.

Troy

protected void btnLogin_Click(object sender, EventArgs e)

       {

           DataProvider dp = new DataProvider();

           SqlConnection kon = new SqlConnection(dp.dbConnectionString);

           kon.Open();

           SqlDataAdapter ad = new SqlDataAdapter("Customers_ByUserName", kon);

           ad.SelectCommand.CommandType = CommandType.StoredProcedure;

           ad.SelectCommand.Parameters.Add(new SqlParameter("@username", SqlDbType.VarChar, 50));

           ad.SelectCommand.Parameters["@username"].Value = txtEmail.Text;

           SqlDataReader reader = ad.SelectCommand.ExecuteReader();

           try

           {

               if (txtEmail.Text != "" && reader.Read())

               {

                   Session["CUST_ID"] = reader["CustomerID"].ToString();

                   Session["CUST_EMAIL"] = reader["Email"].ToString();

                   Session["USERNAME"] = reader["UserName"].ToString();

                   Session["FULLNAME"] = reader["FirstName"].ToString().Trim() + " " + reader["LastName"].ToString().Trim();

                   string paswd = reader["Password"].ToString();

                   string email = reader["Email"].ToString();

                   Decrypto dc = new Decrypto();

                   string ps = dc.Decrypt(paswd);

                   if (txtPasswd.Text != ps)

                   {

                       Default.MessageBox(this, "Invalid password", "key1");

                       return;

                   }

                   else

                       FormsAuthentication.RedirectFromLoginPage(txtEmail.Text, true);

               }

               else

               {

                   reader.Close();

                   Default.MessageBox(this, "Your username have not been registered", "key1");

                   return;

               }

               reader.Close();

               //if this page called from shoppingbag page

               if (Session["CALLEDFROM_SB"] != null && Session["CUST_ID"] != null)

               {

                   //update shopping bag

                   SqlConnection con = new SqlConnection(dp.dbConnectionString);

                   con.Open();

                   string strSQL = "UPDATE ShoppingBag SET CustomerID = '" + Session["CUST_ID"].ToString() +

                       "' WHERE CustomerID='" + Session["CALLEDFROM_SB"].ToString() + "'";

                   SqlCommand cmd = new SqlCommand(strSQL, con);

                   try

                   {

                       cmd.ExecuteScalar();

                   }

                   catch

                   { }

                   finally

                   {

                       kon.Close();

                   }

                   Session.Remove("CALLEDFROM_SB");

                   Session["CALLEDFROM_SB"] = null;

                   Response.Redirect("Shopping_Bag.aspx", false);

               }

               else

                   Response.Redirect("Welcome.aspx", false);

           }

           catch (Exception ex)

           {

               Default.MessageBox(this, ex.Message + " : Failed to get data", "key1");

           }

           finally

           {

               kon.Dispose();

               kon.Close();

           }

       }

# July 31, 2008 3:20 AM

Bertrand Le Roy said:

@Troy: hard to say just looking at your code. Once you've checked all the possible causes described in this post and linked resources, attach a debugger and try to catch thread abort exceptions. If any happen, walk up the call stack and find the culprit. You can also use Fiddler or Firebug to monitor headers for session cookies and diagnose.

# July 31, 2008 1:27 PM

Troy said:

      Hi Bertrand, I only show you the point of losing session while redirect to "Welcome.aspx". I have revised my code.

      If I debug in my local server, I am not losing this session. But after I put this on Web server, the session was loose.

      If I set IE on Privacy -> Advance -> Check Automatic....., this session is exist and run normally on IE Client.

      If I browse with IP number, I am not loosing the session, but If I browse with domain name with redirect, the session was loose.

      How do I have to fixe this problem?. Thx for your time.

      protected void btnLogin_Click(object sender, EventArgs e)

      {

          DataProvider dp = new DataProvider();

          SqlConnection kon = new SqlConnection(dp.dbConnectionString);

          kon.Open();

          SqlDataAdapter ad = new SqlDataAdapter("Customers_ByUserName", kon);

          ad.SelectCommand.CommandType = CommandType.StoredProcedure;

          ad.SelectCommand.Parameters.Add(new SqlParameter("@username", SqlDbType.VarChar, 50));

          ad.SelectCommand.Parameters["@username"].Value = txtEmail.Text;

          SqlDataReader reader = ad.SelectCommand.ExecuteReader();

          try

          {

              if (txtEmail.Text != "" && reader.Read())

              {

                  Session["CUST_ID"] = reader["CustomerID"].ToString();

                  Session["CUST_EMAIL"] = reader["Email"].ToString();

                  Session["USERNAME"] = reader["UserName"].ToString();

                  Session["FULLNAME"] = reader["FirstName"].ToString().Trim() + " " + reader["LastName"].ToString().Trim();

                  string paswd = reader["Password"].ToString();

                  string email = reader["Email"].ToString();

                  Decrypto dc = new Decrypto();

                 string ps = dc.Decrypt(paswd);

                  if (txtPasswd.Text != ps)

                  {

                      Default.MessageBox(this, "Invalid password", "key1");

                  }

                  else

{                      FormsAuthentication.RedirectFromLoginPage(txtEmail.Text, true);

                  Response.Redirect("Welcome.aspx", false);

}

              }else

                  Default.MessageBox(this, "Your username have not been registered", "key1");

              }

          }

          catch (Exception ex)

          {

          }

          finally

          {

              kon.Dispose();

              kon.Close();

          }

      }

# August 1, 2008 5:11 AM

Bertrand Le Roy said:

@Troy: it seems like you're doing everything right here. If you've checked all the references I pointed to, I would suggest you contact support at this point. Feel free to contact me at bleroy at microsoft to tell me how that goes.

# August 1, 2008 1:44 PM

Ahmed said:

i want to define avariable that can use in the other forms in c# application please how,

# January 4, 2009 3:33 PM

Bertrand Le Roy said:

@Ahmed: this should be a good starting point: msdn.microsoft.com/.../ms178581.aspx

# January 5, 2009 3:48 PM

Bruce Cho said:

Found a simple solution.

Instead of using Response.redirect(URL)

Use Server.Transfer(URL)

Seems to preserve

Session[], at least for me.

Hope it helps for you as well.

Bruce Cho

bcho@dialamerica.com

# January 14, 2009 5:45 PM

Bertrand Le Roy said:

@Bruce: sure, transfer always works for session but it's not a redirect, it works on the same request/response as far as the client is concerned and the URL does not get modified, which is the big reason why people use redirects rather than deleting the response and starting over, which is pretty much what transfer does.

# January 14, 2009 6:03 PM

charlie said:

Bertrand, Ive read the article above and am still having some issues.

my session variable works on all my aspx pages but one. the page in question is quite simple. on load, it checks for a session variable but does not find it.

the page contains 2 frames which are simply showing a .htm file each.

i have checked the session id on both the working pages and this page and they all seem to be the same yet i cant seem to pass the session variable to this one page

any ideas?

thanks in advance

# January 27, 2009 3:09 PM

Bertrand Le Roy said:

@Charlie: if you've tried all the advice in this post and read through the comments, you should probably call support. Without knowing what you're doing in that page, there is little I can do. My psychic abilities are not what they used to be ;)

# January 27, 2009 3:28 PM

Rick Connell said:

I have a simple app that logs in a user based upon their email address. (This is not sensitive data) I look up the user in the database and if they are found the session variables are set with userID, FirstName, etc...

I have set the session variables correctly. That is a pretty straight forward process. When I access another page all the variables are null. They don't persist whether I Response.Redirect, Server.Transfer or just type in the next page in the address bar. I am testing on Visual Studio 2008, it is really quite frustrating.

# February 25, 2009 4:28 PM

Bertrand Le Roy said:

@Rick: please read the post. It addresses precisely your problem. What you'll probably want to use is RedirectFromLoginPage.

# February 25, 2009 4:57 PM

Bhushan said:

Hi,

Previously I had worked on

Response.Redirect("admin.aspx");

After adding

global.asax inVS2005

it showed error

Data: error: cannot obtain value

HelpLink: error: cannot obtain value

InnerException: error: cannot obtain value

then i tried working with

Response.Redirect("admin.aspx", false);

and it started working properly.

I now want to know

1.why is this happening, only when i add this syntax

Response.Redirect("admin.aspx", false);

2. I also want to use session variable before Response.Redirect

# March 5, 2009 8:36 AM

Bertrand Le Roy said:

@Bhushan: it's pretty much impossible to tell without knowing anything about your code.

# March 5, 2009 5:43 PM

JOGI said:

When we use response.redirect it send a another request to web from client hidenly.

if you use response.redirect("~/abc.aspx",false)

then you dont get exception thread aborted because now web do not want reply.

Same You can with server,transfer also.

And in response.redirect request scope it end.

but session scope data always there.

So no problem if you are not flow the data using request

JOgi

# March 24, 2009 3:20 AM

sakthi said:

it is not working

# April 24, 2009 7:18 AM

Bertrand Le Roy said:

@sakhti: sorry to hear that, but what exactly is not working, and how?

# April 24, 2009 1:42 PM

Dima said:

Hi Bertrand.

Having same problem. Using redirect ("xxx.aspx", false), but sometimes Im loosing session value on A HREF link.

How is it possible?

thx

# April 29, 2009 2:44 PM

Bertrand Le Roy said:

@Dima: could it be a timeout?

# April 29, 2009 2:49 PM

Dima said:

No.

This happening after 2 minuts I logged in, and timeout configured for 60 minutes. Also, Im checkin with Session.SessionId, and it's always there, same string, never lost, but values from Session("logged") or ("UserName") are gone, NULL.

# April 29, 2009 2:52 PM

Bertrand Le Roy said:

@Dima: let's follow-up offline. You can send me mail at bleroy at microsoft.

# April 29, 2009 3:37 PM

NIC said:

So how do you get this to work with classic asp

# May 19, 2009 12:21 PM

Bertrand Le Roy said:

@NIC: I don't know, I haven't touched classic ASP for about 6 years.

# May 19, 2009 1:21 PM

Smiley said:

I am not sure if its related. But I have a typical problem. I have a static class and a static session property created in it(just to keep it generic and accessible at various places on website pages). There's a user control on master page, and I invoke a static method of this static class, to get/set this session property. The point where it either gets or sets this session, I get a null reference exception.

That somehow doesn't break the flow due to some reasons not aware.I don't get the exception if I call the same static method at the page level (content place holder for the master page).I am using 'stateserver' as session mode. Now this scenario doesn't happen when I do it from my machine. But it happens when I deploy on prod environment. Right now I have resolved it by placing a try catch around the property get/set, so that it suppresses the exception and error stops flowing in error log. I am sure there has to be a better solution for it. I am just curious about the reason why it happens, is it somehow related to the explanation you have given above?

# July 6, 2009 3:00 AM

Bertrand Le Roy said:

@Smiley: static properties in web apps? That's asking for trouble: you'll have thread safety issues, and you may force object lifetime to be longer than it should be (objects in web environment should typically not live longer than the current request). AppDomain restarts may also break your expectations.

Session is very easily available from anywhere through HttpContext.Current.Session.

# July 8, 2009 7:53 PM

Gerardo said:

If you have this problem using a IIS or Apache server in Windows try to look  at the URL where you are redirecting it must be writed in the same way as the URL from you are redirecting.

site.com/pages/index.php redirection to site.com/Pages/index2.php is going to loose the session in IE7 because the capital letter in Pages

# July 14, 2009 2:29 PM

Kenny said:

I'm using a custom session object class called "UserSession" to manage my session data (I can send you the sample code if you need to see it). It seems to work fine if I never have to change any of the session values. But once I try to update the session object values, it goes twilight zone on me.

Example: If I select job #1 from the job listing page, I set the UserSessionObj.UserInfoObj.JobID to the selected JobID, so as they browse around the site to the any of the 300 forms, I always know exactly which job they are trying to view. On each page load, I get the UserSessionObj.UserInfoObj.JobID value and do my SQL calls to load the form data.  After a user has selected and viewed a few jobs, the current session values appear to randomly get mixed up. It's a roll of the dice which job loads when I visit the pages. It's not as if the JobID session data disappears, because it's not blank, it simply reverts back to session data values I selected earlier in my session. Sometimes it feels as if I'm not updating the session object correctly and I'm inadvertently creating more instances of the same object, so the browser gets confused as to which instance to load. Does any of this make sense? Any help would be greatly appreciated. I need to get away from my http cookies.

# August 3, 2009 2:02 AM

Bertrand Le Roy said:

@Kenny: hard to say, but I'd guess static variables in your code.

# August 3, 2009 2:43 AM

Kenny said:

But I have no static variables. I have noticed something though in the past 30 monutes or so. I created a page called "test.aspx" and it does nothing but display the session data to a label. After I hit the refresh button a few times (usually 3 times), it errors out and says the session object doesn't exist. What would cause the object to disappear?

# August 3, 2009 3:03 AM

Bertrand Le Roy said:

@Kenny: no idea then, sorry. Web farm?

# August 3, 2009 3:19 AM

Kenny said:

No, a single server running two websites. I don't know. I'm just tired of looking at the same code for 45 straight hours. A million websites using session variables without incident, and mine is being a pain in the arse. I have to have this running by morning and it's getting worse, not better!

But thanks for your help! :-)

# August 3, 2009 3:27 AM

Bertrand Le Roy said:

@Kenny: you should probably contact support. contact me if you don't know how.

# August 3, 2009 12:22 PM

Sanjeeb said:

Dear Bertrand,

I have this in my web.config:

<customErrors mode="On" defaultRedirect="Forms/GenericError.aspx"></customErrors>

And this in my Global.asax:

void Application_Error(object sender, EventArgs e)

{

   Exception ex = Server.GetLastError().GetBaseException();

   HttpContext.Current.Session[“LastException”] = ex.Message;

}

And this in my GenericError.aspx:

protected void Page_Load(object sender, EventArgs e)

{

   object lastException = Session[MNPSessionConstant.LastException];

   if (lastException != null)

   {

       this.lblErrorMessage.Text = (string)lastException;

   }

   Session[“LastException”] = null;

}

Now when I get to the Page_Load of the error page for the first time I always get the session variable as null. But if I click the back button and go to the previous page and the do the same exception throwing activity again, I get to see the session variable value in the error page.

Could you please help me understand why this is happening?

Regards,

Sanjeeb

# October 16, 2009 5:56 AM

Bertrand Le Roy said:

@Sanjeeb: I don't know but I'd suspect the error redirect is not using the overload that doesn't terminate the response. You might want to consider storing the error in another container than session.

# October 16, 2009 2:37 PM

Greg Vestal said:

I have what appears to be a unique issue which I have pretty much written off to the user's system setup.  We have an apartment application here that works fine for 1000s of users without this problem.  Also works in production with anybody else here loggin into their profile.  It seems that a session variable is changing between page posts.  Basically we have a customer they login, they choose a property and the next page is a list of units in that complex.  Well what is happening is the units that come up on the next page are from a different complex.  I have never heard of the session variable changing like that.  I haven't checked the system set up yet but was wondering if you have any idea what might be causing this??  This is VS 2002 written in VB.NET.

# November 3, 2009 3:27 PM

Bertrand Le Roy said:

@Greg: I'd bet for caching. Probably too aggressive.

# November 3, 2009 3:35 PM

etam said:

I'm getting the same problem on production server.on  localhost it is working fine . do you suggest to use server.transfer instead?

# November 4, 2009 2:21 PM

Bertrand Le Roy said:

@etam: no, except if transfer was the right thing to do to begin with. They are not interchangeable.

Do a redirect (with the right overload) when you want the URL in the browser to reflect the change, and do a transfer if you want to delegate the processing of the current request to another handler or page without it being reflected in the URL. Those are two very different use cases and one should not switch just to work around a bug. Fix the bug instead :)

# November 4, 2009 2:31 PM
Leave a Comment

(required) 

(required) 

(optional)

(required)