Tales from the Evil Empire

Bertrand Le Roy's blog


Bertrand Le Roy

BoudinFatal's Gamercard

Tales from the Evil Empire - Blogged

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;
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.
UPDATE 3: It appears like some bug fixes to Session have permanently fixed this problem. At least the one caused by the thread aborted redirect. Still, it is good practice to not abort the thread (and thus use the overload with the false parameter).


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);

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

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

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

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

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



# December 2, 2006 6:05 AM

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:


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;




in error.cs

protected void Page_Load(object sender, EventArgs e)


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






This does not work:


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;




in error.cs

protected void Page_Load(object sender, EventArgs e)


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






==> 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.


protected override void Render(HtmlTextWriter writer)


           if (!Response.IsRequestBeingRedirected)



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()







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,


# 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,


# 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

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;


       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:


I'm Using the following code..

Session("Test") = Value


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,


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

Bertrand Le Roy said:

Prasad: what's this 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

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

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?


# 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:

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

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


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";


               case "a":

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



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





   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) {




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) {




# 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["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["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;


Third time you load the page:

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


# 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:


...should be...


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

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"


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



# 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

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:



protected void btnLogin_Click(object sender, EventArgs e)


           DataProvider dp = new DataProvider();

           SqlConnection kon = new SqlConnection(dp.dbConnectionString);


           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();



               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");




                       FormsAuthentication.RedirectFromLoginPage(txtEmail.Text, true);





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




               //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);


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

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

                   SqlCommand cmd = new SqlCommand(strSQL, con);






                   { }






                   Session["CALLEDFROM_SB"] = null;

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



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


           catch (Exception ex)


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








# 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);


          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();



              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");



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

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



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



          catch (Exception ex)









# 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


# 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:


Previously I had worked on


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

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?


# April 29, 2009 2:44 PM

Bertrand Le Roy said:

@Dima: could it be a timeout?

# April 29, 2009 2:49 PM

Dima said:


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?



# 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

Mark said:

For classic asp guys....Max solution from October 2007 and confirmed by Jim in 2008, has worked for me in 2009.

That is SessionIdNumber=Session.SessionId at top of page.

The gift that keeps on giving.

# December 2, 2009 10:17 AM

Martin said:

Hello, this was a old blogg post but i give it a try anyway.

We have a similar problem at our production servers. We can't recreate the problem in our test environment so we are fumbling in the dark here. The thing is that our problem only occurs to some customers. They log in and after the redirect they are logged out right away. Seems to be some kind of session problem. I have 2 questions.

1. It seems like the problem started when there was an upgrade on IE8. Could the IE-client affect this in any way?  

2. In the past we had a problem that the memory on the servers disappeared and the application crashed. After a while we found that it was the response.redirect that was causing the problem. The solution was to rethrow the ThreadAbort exception to the framework (we catched it before). After this workaround was applied the memory problem disappeared. But if we use Response.Redirect("~/default.aspx", false); don’t we get the same problems with threads that are not aborted correctly and eating our memory?

# February 8, 2010 4:59 AM

Bertrand Le Roy said:

@Martin: I have no idea how IE8 would affect this, but it seems like you're programming by coincidence here. The point of aborting the thread is not to force the framework to clean up after you. The point of the thread abort exception is to stop the lifecycle of the request where it happens. It's rather heavy-handed and is mainly there for back compat with classic ASP. You should use the override that doesn't abort the thread and figure out what in your code is leaking memory. Tools you can use for that include debuggers and profilers.

# February 8, 2010 1:36 PM

Hannah said:

Hi Hi,

I have a really strange problem to do with session variables.

I have an asp.net page that sets a few session variables. On my development machine (localhost),  I do a postback and the session values are still populated.

When I Reload the page by clicking on the url bar and pressing enter the session variables are still there.

However when i deploy this page to a webserver, the page still retains the session values when doing a postback, but as soon as i click the url and press enter the session values are lost (where the ispostback = false)

But when i press the refresh button the session variables are present (but i do get a popup warning me that the page data needs to be resent!)

i am running IE 7, and the webserver is iis6 what am i doing wrong?!

please help x

# February 27, 2010 10:57 AM

Bertrand Le Roy said:

@Hannah: that sounds a lot like you're getting a cached version of the page. The easiest way to be sure what you're getting when refreshing comes from the server and not from the browser's cache is to use CTRL+F5. But even then, you might get the page from a proxy's cache or from server cache. For that, I'd check the caching policy on the page.

# February 27, 2010 1:36 PM

Rubén Aláez said:

Hi, we have a similar problem. We have some session variables, but when the page redirects to Mastercard page to make the payment, all session variables are lost.

After the payment, Mastercard page redirects to our page (I don't know what kind of redirect are they using) and we lost all the session variables.

Is there any solution for us?

Best regards and thank you very much.

# March 2, 2010 6:30 AM

Bertrand Le Roy said:

@Rubén: are you using the overload with false as the second parameter?

# March 2, 2010 2:42 PM

Bertrand Le Roy said:

@Rubén: then I don't know, sorry. You should probably contact support.

# March 3, 2010 1:21 PM

The Dude said:

I don't know about anybody else but this works just fine for me:

I have a WebForm (Form1.aspx) that is redirecting to Form2.aspx.

In Form1.aspx I have:

protected void Button1_Click(object sender, EventArgs e)


Session["ID"] = 24;



In Form2.aspx I have:

protected void Page_Load(object sender, EventArgs e)


int id = Int32.Parse(Session["ID"].ToString());


The id variable sets to 24 in WebForm2.aspx.

So all I can say is... "It works for me."

# March 11, 2010 11:35 AM

Bertrand Le Roy said:

@Dude: yeah, that's the point, it *seems* to work, but it doesn't always. It works when you already have stuff in session, because your already have the session cookie. When it fails is when the session is getting created right before the redirect. That example of yours should definitely use the overload.

# March 11, 2010 7:25 PM

a guy said:

I somehow lost the sessionstate configuration line in my web.config and found that to be the problem in my case

# March 31, 2010 3:47 PM

joss said:

hi, but what is that rare case it does not work. i also tested with framework 1.1 and 2.0 and it works fine. using the thread aborting redirect() does not cause the session cookie lost.

# April 5, 2010 12:14 PM

Bertrand Le Roy said:

@joss: it seems to work in a development environment because most of the time, if you don't delete your cookies, you already have a session cookie, so it doesn't manifest itself (a redirect won't make you lose existing cookies, it will just prevent new ones from getting created during that request). In other words, your users are likely to hit it before you do, which is the worst situation. Just use the non-aborting overload.

# April 5, 2010 1:57 PM

joss said:

i am clearing cookies from browser. check the following code. session is never lost. may be those rare cases are coming out because maximum compilations for restart.

- sessiontest.aspx

       string cookieVal = Request.Headers["Cookie"];

       Session["var"] =

           "<br>Previous val: <i>" + Session["var"] + "</i>" +

           "<br><br>Time: " + DateTime.Now +

           "<br>IsNew?: " + Session.IsNewSession +

           "<br>SessionID: " + Session.SessionID +

           "<br>Cookie: " + cookieVal;


- sessionredir.aspx

       string cookieVal = Request.Headers["Cookie"];

       Response.Write("<br>Session Var: <b>" + Session["var"] + "</b>");

       Response.Write("<br><br>Time: " + DateTime.Now);

       Response.Write("<br>IsNew?: " + Session.IsNewSession);

       Response.Write("<br>SessionID: " + Session.SessionID);

       Response.Write("<br>Cookie: " + cookieVal);

# April 6, 2010 3:52 AM

joss said:

i have tested a lot of scenarios and could not come up with one that session is lost after redirect that ends the response(aborts thread).

i have cleared cookies from the browser before testing each scenario.

i have used iis5.1 + ie6 and iis7 + ie8.

so you should review the article and point out what are those cases (if still exists) that causes session lost?

at least response.redirect that ends the response do not cause session lost. so, please clarify your assertion to avoid confusions.

thanks in advance

# April 6, 2010 9:00 AM

Bertrand Le Roy said:

@joss: I wasn't making that stuff up, it came from actual verified support cases. But you are right that I didn't verify it since I wrote the article 6 years ago. Thanks for pointing it out. I just did verify, and it seems like the cookie is now being set even when redirecting with the thread abort. Something must have changed in the code. I'm investigating and will update the post accordingly.

# April 6, 2010 2:07 PM

KYankee said:

After digging for hours, I found that the worker threads in the app pool was set to 4. I set it to 1, and now it works fine. My issue was that my web page would find the session variable, and sometimes it wouldn't. By hitting F5 it would almost be every other time it would have the session var, but with only having 1 thread, it's there every time. Makes sense to me. Just took a long time to figure that out.

# April 6, 2010 2:18 PM

Bertrand Le Roy said:

@KYankee: ah, but that's session affinity in a web garden, that's a whole different issue. When using a web garden or web farm, you need to switch to a different session store than the default in-memory one.

# April 6, 2010 2:23 PM

Bertrand Le Roy said:

@joss: depends on what you're trying to achieve, but you can usually refactor to eliminate the need to abort the thread. The easiest (but not necessarily the cleanest) is to set a flag to neutralize further treatment.

I don't see that being deprecated. It's still there for classic ASP compat.

# April 6, 2010 5:15 PM

davidshq said:

Hmmm...I'm having a similar session issue, but it appears to be caused by telling a wizard what is the activeviewstep....is there a way to prevent this in the wizard control?

Dave (dmackey AT NOSPAMpbu.edu)

# April 15, 2010 8:24 AM

Thilaga said:

I am also really fed up with Session variables(in localhost itself). I have changed my code from Redirect to Server.Transfer, then session value will be retained. But the url path , flow and navigation is wrong.

Finally i am planning to go for Global variables instead of session.

What is your advice?

# June 2, 2010 9:17 AM

Bertrand Le Roy said:

@Thilaga: don't. Global variables come with all sorts of problems (thread safety being one of them). My advice is in the post: don't use Transfer but use the overload that doesn't terminate the thread instead.

# June 2, 2010 10:17 AM

Kushal said:

Hi ! I am new to developing application with Visual Studio 2005. Currently I have created a small login application (asp.net web application). I have publish the website.Login page gets opened whenever URL is started but I am facing problems in redirecting the user to a page after he successfully login into the account.Error "Page cannot be displayed" is displayed. Where may be the issue ? Pls help

Any help is appriciated. Thanks in advance.



# June 4, 2010 3:59 AM

Bertrand Le Roy said:

@Kushal: it's impossible to say with what little information you provided. There probably is a bug in the page you're redirecting to, which you can see by setting customErrors in web.config. Then debug and learn I suppose. One thing to check would be whether that page works at all if you remove the requirement to be logged in.

# June 4, 2010 1:58 PM

Joerg said:

I have the same problem and already tried the overload version of Redirect, but it doesn´t work either. If have an application where the user has to fill out some forms. The application has 4 pages. The first Redirect works, the second one works when the user doesn´t wait longer than a few seconds. But when he waits for half a minute or longer, the session variable is not filled anymore. If have set the timeout in my webconfig at 300. The result is the same. It always works on localhost, but not on the server. Any ideas?

# June 28, 2010 7:32 AM

Bertrand Le Roy said:

@Joerg: you should contact support.

# June 28, 2010 10:58 AM

Nahu said:

Thanks alot for the updates. I had an underscore in my hostname and it would have taken me ages to find that out.

# August 26, 2010 8:43 AM

john barnes said:

Hi Bertrand: Believe it or not, there are still "legacy" Classic ASP apps out there, although like objects at the outer reaches of the universe, they seem to be accelerating away at ever increasing speed :(

I've been trying to track down this session-loss issue ever since migrating a working website from server 2003 to server 2008 recently. Something has changed in IIS's handling of sessions between the two platforms, and it is unrelated to .NET framework.

It seems that server 2003 _would_ persist the same session ID between http and https redirects or pageloads (within the same FQDN), but in server 2008, two separate session cookies seem to be being written, one for http and one for https. And these session cookies are persisting, so that if you bounce back and forth between http and https (even on the same page), you will retrieve two separate session IDs.

If this is by-design, it's not how it worked on server 2003, and unfortunately, it appears that some of us relied on this behavior to maintain sessions when redirecting between secure and insecure pages. I've only verified this on Server 2008 Standard SP2 and Server 2008 R2 Standard 64-bit editions, but I expect it is the same on other versions.

I don't expect you to have an answer, and I'm not sure if it's even worth trying to get "fixed" or not, but I'm hoping that people experiencing the problem will stop tearing out their hair. If you're experiencing this behavior on 2008, rolling back to server 2003 may be the only answer for now.

# October 11, 2010 7:46 PM

Bertrand Le Roy said:

@John: not only do I believe that but I know it: I've seen the numbers. Anyways, I can't help you much here, you should contact support, they'll help you. Classic ASP is still supported.

# October 12, 2010 2:54 AM

Laique said:

I am facing the same problem, can any one help ?

I am

SessionIDManager Manager = new SessionIDManager();

                       string NewID = Manager.CreateSessionID(Context);

                       string OldID = Context.Session.SessionID;

                       bool redirected = false;

                       bool IsAdded = false;

                       Manager.SaveSessionID(Context, NewID, out redirected, out IsAdded);

Session["WebUser"] = logName;

                               Session["Usertype"] = logType;

  Session["Auth"] = true;

Response.Redirect("./AdminPage.aspx"); or Response.Redirect("./AdminPage.aspx", false);

In adminpage.aspx i am not getting the session variable

What should i do ?

I want to change Session id after success login but also want my session variable in new page.

How can I do ?

Pls. Help

# November 4, 2010 7:53 AM

Bertrand Le Roy said:

@Laique: what's all that stuff with SessionIDManager supposed to do?

# November 4, 2010 11:52 AM

Andy said:

I have the same issue and tried all of the "solutions" posted.

Is there anything else that could be causing this?

# December 3, 2010 3:45 PM

Bertrand Le Roy said:

@Andy: if you've tried all the solutions above and they didn't work for you, please contact support.

# December 3, 2010 3:51 PM

Andy said:

Thanks for the reply.  I can post some of my code:

This is part of my Default.aspx:

//  button click handler is executed

Session["userSession"] = userSession;

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

This is part of the WelcomePage.aspx:

protected override void OnInit(EventArgs e)


 UserSession userSession = (UserSession)Session["userSession"];

//  test to see if the userSession is null.  If it is,

//  then send them back to the login page.



The "userSession" is only null on the initial try.  After that it works fine.

Any idea where I am going wrong?  

Thanks again for your help.

# December 3, 2010 4:02 PM

Bertrand Le Roy said:

@Andy: nothing strike me as utterly wrong. Ah, caching maybe? Do you have any caching on those pages, or maybe configured in IIS?

You should contact support, they will help you.

# December 3, 2010 4:10 PM

Ken Forslund said:

Looks like I hit the problem on on VS2010 C# .net 3.5 site.

I got it solved.

The short of it is this.  Have your master page or regular pages look for your UserID (or whatever token you pass to yourself) in the session.  if it's missing, do a Server.Transfer to your login page.

In your page_load of the login page, capture this.Page.PreviousPage into a hidden variable (and set it to ~/Default.aspx it it's null).

Also be sure to clear out your Session's UserID (this initializes it)

In your Login button handler, after you've verified the credentials, set the UserId in your session.  Then do a Response.Redirect() back to your Previous Page (that you kept in a hidden variable).

Because the Login page is actually 2 loads (1st load, and a postback), this initializes your session for you.  

Finishing the 1st load (rather unload) gets the cookie in place.  It'll still be empty when you postback (but you aren't needing it yet).  Because the cookie is in place, when you finish yoru postback, your session will stick.

# December 27, 2010 4:34 PM

rothen_s said:

I had the same problem and a Response.Redirect(..., false) did not work for me (ASP.NET 2.0.5, IIS version unknown). In the end I solved the problem with a trick: I made a aspx.page only to start the session. This page basically consists of a a dynamically generated metatag which makes the redirect instead of a Response.Redirect. A detailed description of this solution (although in German) and the code can be found when you click on my name.

# January 30, 2011 7:11 AM

Amit said:

One thing to add is ensure we dont have session.abandon written on the page as it clears the original session id and issues a new one; the request has still not gone to the browser the new session id is not available on the next page which results in loosing the session altogather

# February 5, 2011 3:11 PM

shrikant said:

Hi Bertrand Le Roy,

i am facign the same problem. I am redirecting from one page to another page of different server. But i need to set some session variable before redirecting to page of another server. like

http:www.example1.com/default1.aspx to


I had session mode as Inproc which i changed to sqlserver. then also session variables got cleared in redirect. Please help me in this. Thank you in advance.

# August 2, 2011 12:58 PM

Bertrand Le Roy said:

@shrikant: if you tried all the solutions in the post and it didn't work, please contact Microsoft support.

# August 2, 2011 4:42 PM

dave nelson said:

i have a domain name pointing to a web server running an  ASP.NET 4 application, authenticating using the ASP login control.... everything works fine.

then, i created a second domain name and in a DNS server, i pointed this second domain to the first, symbolically (no ip address).  using this second domain, i connect to the web app ok, but aftyer login, the cookie gets lost because Page.user.identity.name comes up blank on the redirected page.

any ideas?

# August 16, 2011 11:09 AM

Bertrand Le Roy said:

@Dave: yes, that's 100% expected. Session cookies don't survive a domain transition, even if the server is the same. You'll have to find another way to do whatever it is you are trying to do.

# August 19, 2011 5:07 PM

Zeeshan Umar said:

Nice post, It solved my problem, i was looking for many hours that why session value is acting weird.

# August 30, 2011 4:44 AM

labshasan said:

# September 8, 2011 8:03 AM

Bertrand Le Roy said:

@labshasan: the solution in that thread is just horrendous, and nobody should follow those directions.

# September 14, 2011 4:31 PM

Mark Morgan said:

Still after reading this very long thread and doing all possible solutions still failed.

I have no problem running the site localy with the url as IP. When I publish and used the url as masked thats the only way my session variable is set to null.

I have tried passing them as url parameters and assign them to session variable on the load event of the redirecting page. But still Session variable is empty. I have also noticed that if I done it twice session now have values and not have value null.

It is not ideal to let the user login twice.

# September 18, 2011 1:27 AM

Bertrand Le Roy said:

@Mark: you should contact support.

# September 18, 2011 2:04 AM

Chandra Prakash said:

Session is working well for 2 minutes.. But After 2 minutes it showing nullrefernce exception..at server..

i have increase time to 20 minutes still session is termenating after 2 minutes.

It is working well at Local but not at the server

# October 1, 2011 5:56 AM

Bertrand Le Roy said:

@Chandra: this is a different issue. Please contact support.

# October 1, 2011 4:46 PM

Alex said:

Although this is very old thread, but i would like to add something here. I am having the same problem of session loss but not in the exact scenario. I create a session variable in asynchronous callback and I sometimes do not find this variable.

Let me try to work is around to get confirmed if this is the reason.



# March 11, 2012 7:41 AM

Marcela said:

I fix this problem on VS 2010. I was loosing the session, but not always. The problem was when using chrome and ie 9. It was because sometimes the browser doesn't accept the session cookie, that's why it works in some browsers and not in others.

When the server doesn't see an ASP-session cookie, it creates a new session and the data is lost. My solution was to create the "ASP.NET_SessionId" cookie right after the user is authenticated with the current Session.SessionId

Response.Cookies.Add(New Web.HttpCookie("ASP.NET_SessionId", Session.SessionID))

That fixes the issue in my case, I also used the false parameter in the response.redirect

Hope this helps other people. It took me 4 days to find the right solution. I tried different ways without success

# March 30, 2012 5:11 PM

albgen said:


I'm having the same problem but it's very strange.

It work on almost every computer except some.

Different computers but same browser, on some works, on others dont...really frustrating this issue...

Any idea?

thank you

# April 2, 2012 9:27 AM

arsalan said:

i have similar problem with asp.net profile object when i redirect page from login page by using Response.Redirect("admin.aspx",false) it loses profile object data, please Any valid explanation for this?

# June 6, 2012 7:11 AM

Bertrand Le Roy said:

@albgen: cookies are per domain, that's why. You should have redirects from one to the other anyway for good SEO.

@arsalan: profile uses cookies to track you, so they have the same issues as session.

# June 12, 2012 3:51 PM

Scott said:

I encountered a problem where occasionally all Session values (including Authentication) were lost when navigating to a single page on my website. It was next to impossible to reproduce but I finally discovered the problem.

The problem was occurring because the link to the troublesome page contained the full URL path (not relative path) but without the "www" prefix. So when a visitor navigated to my site using a link starting with "www" all was good as they navigated my site using relative paths links (ie: "~/Home"), but as soon as they clicked the problem link without the "www" prefix (ie: "mydomain.com/SomePage") the Session was lost because the server views this as a domain redirection.

I fixed the problem by adding a rewrite rule to my web.config file to remove "www" from all server requests.

The reason for the full URL path is because I'm using URL Routing and a relative path does not always resolve correctly when using relative paths.

I hope this helps.

# August 2, 2012 3:01 PM

Scotts said:

I encountered a problem where occasionally all Session values (including Authentication) were lost when users navigated to a specific page on my website. It was next to impossible for me to reproduce but I finally discovered the problem.

A new session was being initialized when users clicked on a link that contained the full URL path including the domain name but without the "www" prefix. Whenever a visitor navigated to my site using a url link beginning with "www" (ie: "www.mydomain.com/Home") all was fine until they clicked on a link without the "www" prefix (ie: "mydomain.com/SomePage") at which point all session data was lost because the IIS server considers this to be a domain redirection and initializes a new session.

The problem was easily fixed by adding a rewrite rule to my web.config file to remove "www" from all server requests.

I hope this helps.

# August 6, 2012 12:16 PM

Prathap said:

In my Login page.. below is the code for login button

protected void btnlogin_Click(object sender, EventArgse)


       Session["name"] = txtuid.Text;



Then tried to retrieve it in Products.aspx page

lbl.Text= Session["name"].ToString();

but same error...Object reference not set.

Can you please help me. I am using Mozilla browser.

# September 17, 2012 10:32 AM

Bertrand Le Roy said:

@Prathap: Contact Microsoft support.

# September 20, 2012 3:05 AM