Session.Start called on every request when fired - asp.net

I've got a "works on my machine" situation.
I have a website where I'm passing session values from one page to another using
Session["foo"] = 'blah';
and on page2
var foo = Session["foo"];
foo doesn't exist on page2.
When tracing the page I've found it was using a different sessionid to the original page. When putting a breakpoint on Session_start it looks like for each request the page is starting a new session.
This does not occur on my machine... and thoughts on what I can do to solve on other machines?
The SessionState is InProc
Page1.aspx and Page2.aspx are both
part of the same website and
Privacy
is set to accept all cookies on the
target machine.
EDIT: Difference between running on my machine and target is that I am using http://localhost/blah locally and http://XX_0001/blah from the other client where XX_0001 is my machine

Well I think I have found the solution:
It looks like the _ in my machine name is causing the issue. Seems that hostnames do not allow underscores: http://www.faqs.org/rfcs/rfc822.html

My first guess would be to check to see if cookies are enabled on the computer that is having the problem. Does it work in other browsers etc?
If you're changing the url as well, ensure that you're still on the same site because different sites will use different cookies.

I thought the string indexing Session was case sensitive. You've got "foo" and "Foo". Is that a typo?
Otherwise, cookies would be my guess as well.

Related

Session values are lost between calls

Due to an unknown reason, my website does not send ASP.NET_SessionId cookie to browser neither on local debugging IIS nor on deploying IIS, therefore my Session is always empty on each page. In IIS preferences 'Session state' is set to 'In process' (sorry, maybe not exact translation, I have localized IIS). Any ideas on this matter?
ADDITION 1: Well, I switched sessionState mode to <sessionState cookieless="UseUri" />. Url address in browser now contains (S(fn215g55r4kws155lbfaxf55)) tag, but Session property of the ASPX page is empty ANYWAY. So... my website is still sessionless without any obvious reason.
ADDITION 2. I created blank website on the same debug server and session cookie works okay there - values are persisted between calls. So, the problem is related to my main website or its web.config, I believe.
ADDITION 3. As mentioned #Damien_The_Unbeliever, the problem is really related to setting values. I do not know why, but session is completely ignores line Context.Session[promoCodeSessionKey] = (int?)promoCode.Id;. No cookie is send after this line. But if session is already created in another place and cookie is set, this line will work correctly.
ADDITION 4. I found the reason. See the answer below.
WOOHOO!! I found the reason! There was EnableSessionState="ReadOnly" directive in ASPX's <%# Page tag. Please pay attention, that a) because of this Session was not working on master page as well, and b) there are no exceptions!!

ASP.NET session lost after redirect but only with IE

Everything in italics is the original post, edits below are non-italicized
I am writing in C# using ASP.NET 4.0.
I am authenticating user credentials via SQL lookup and if valid I am storing the username in a session variable then redirecting the user back to the main page. Pretty simple.
if (!db.isValidLogin(userName, passWord))
{
//invalid login, show it!
//just some code to tell the user invalid credentials
}
else
{
//show login successful!
//update some items on the screen
Session["username"] = userName.ToUpper();
Response.Redirect("/");
}
This is not yet over SSL as it's internal development at this point.
When I use Chrome Version "25.0.1364.172 m" I am properly redirected and I am "logged in". My screen is representative of that by showing me my user name and allowing me access to features that authentication allows.
When I use (32-bit) IE 9 Version "9.0.8112.16421" with the same server side code and procedure... When I do the redirect my session variable "username" is gone. In fact the session has a count of 0 for items. BEFORE the redirect the session variable is set and it is correct.
I have the same results on a Windows Server 2008 R2 64-bit box and a Windows 7 64-bit box.
I am using a single server hosting both IIS and SQL. I am not using a session server.
I have traced it out... the code is running exactly as desired up until the redirect. Receiving credentials, executing my stored procedure to validate... setting the session variable before redirecting (I can see the session and the variable and the value is correct).. and then redirecting... and as stated, with Chrome it works EXACTLY as desired... with IE the session is lost on redirect.
I have tried this as well with no success:
Response.Redirect("/", false);
So I'm convinced that something IE is doing, maybe with setting cookies on the client, that is causing a mismatch between the browser and the server session.
Should I not be doing a response.redirect??? And if I do a response.redirect, how do I keep the session from resetting? Once again, keep in mind this doesn't happen when I use Chrome.
Frustrating...
Thanks for any help!
NEW INFO
After attempting to turn off IE caching per an answer... I decided to output the sessionID to the browser so I could see what it was.
The behavior is more direct that the login and redirect...
In IE simply refreshing the browser with F5 causes a new session to be created on the server. Each refresh I receive a NEW session ID.
Testing this with Chrome I do not get a new session ID unless I call session.abandon, timing out my session or closing and restarting the browser.
I was only calling session.abandon when the user clicked log out, but have commented out that code (just in case) to ensure that I'm not abandoning it on accident.
Somewhere between actual page refreshes IE is presenting itself to the server for a new session... ARGH.
For example:
Chrome:
Before login: myjuzrmccerk1t4eakcliq14
After login: myjuzrmccerk1t4eakcliq14
IE:
Before login: unyebuc2ikac12xnhpssy0em
After login: unyebuc2ikac12xnhpssy0em
Refreshes with F5 or Ctrl-R:
one: ptjt42fjwzgdreyyyo3cmvrs
two: s1hd5aatl5yexeuc125aqhst
three: kbpflurcdcxubux3scmdm4k5
Update 2
I have changed the site to use "State Server" for the session and started the appropriate service... There is no change in behavior.
ANSWER
Since my rep is low.. .this won't let me answer my own question for another 3 hours... but here it is..
I found a fix... through trial and error.
InProc and StateServer in sessionstate both had the same results until I added "cookieless=true"
<sessionState mode="StateServer" cookieless="true" />
This causes the session state to be consistent in both Chrome and in IE (where the problems was) and my session ID no longer changes between page refreshes. I was unable to determine WHY this happens, but it is fixed nonetheless.. Thanks Mike and antinescience for your help!
InProc and StateServer in sessionstate both had the same results until I added "cookieless=true"
This causes the session state to be consistent in both Chrome and in IE (where the problems was) and my session ID no longer changes between page refreshes. I was unable to determine WHY this happens, but it is fixed nonetheless.. Thanks Mike and antinescience for your help!
There are some other reports that indicate that IE's caching mechanism (which is widely regarded as, well, not great) may be to blame here. Can you try appending the following to your page:
// Stop Caching in IE
Response.Cache.SetCacheability(System.Web.HttpCacheability.NoCache);
// Stop Caching in Firefox
Response.Cache.SetNoStore();
...and see if that has any effect? The other alternative is you could do:
int randomNumber = new Random().Next(1, 1000);
Response.Redirect("/?nocache=" + randomNumber);
...just for testing. Heck, you could slap the date as numeric in to test as well.
i had the same problem for couple of days now and finally i knew the reason why the session was changed each refresh, first after using the Response.Redirect( URL ,false) method i realized that i was entering the URL as AbspoluteURI as "http:// ServerIP/File/Page.aspx" , i used the AbsolutePath method instead as "~/File/Page.aspx", and my problem was solved!! the IE thinks that the server was changed when you write AbsoluteURL instead of AbsolutePath, i wish this could help
I had the same problem with a webpage which was hosted inside an IFrame. Troubleshooting showed that the ASP.NET Session cookie was lost along the way, and it only happened when using Internet Explorer. When I opened up my webpage in a separate tab in IE everything worked fine.
The problem was caused by security in Internet Explorer. It will not persist cookies unless there is a P3P HTTP header. You can see the blocked URLs by going to IE->View->Webpage privacy report..., and there choose to show "Restricted websites".
I solved the problem by adding a dummy P3P header with every request. The header looks like this;
P3P:"Bogus P3P header because Internet Explorer requires one"
This is the same approach as facebook.com uses. Their p3p header looks like this;
p3p:CP="Facebook does not have a P3P policy. Learn why here: http://(...)/p3p"
See also Cookie blocked/not saved in IFRAME in Internet Explorer
I had this issue too, this SO response solved my problem. If your hostname has underscores (which seems to be invalid), IE seems to drop the session (!).

Check cookies in asp.net

I want to check if a user has cookies enabled.
Most solutions involve:
1. creating a cookie
2. redirect the user to a custom page or the same page.
3. Read the cookie.
The issue I have is in the 2nd step. Should I use a query string while doing a response.redirect so that in the next trip I know the cookie has already been set and that I should try to read it? What if the user hard codes the URL(along with that query string) in the browser, while accessing the website?
Also, if I find that the cookies are enabled and I set a session variable to say that cookies are enabled on this browser, so dont check again in that session. Is that OK?
If session is available, is that a good enough indicator that cookies are enabled?
I want to minimize these double trips to each page for checking cookies.
I would use javascript to make an asynchronous request and check to see if the cookies that were set were handed back in this request.
Never pass a querystring. You already hinted at it above, but what if some trickster figures our the url and decides they want to pass their own querystring?
If the user has cookies set up, you can set the session and check that.
Always check the session.
instead of using this technique which involves multiple steps and pages, and extra waiting time for the enduser, can't you just use the HttpBrowserCapabilities class? This particular class has a Cookies property:
HttpBrowserCapabilities.Cookies Property
Grz, Kris.
As per my knowledge I know Two ways to check whether browser enables/accepting cookies
By using "Request.Browser.Cookies"
By using Javascript/Jquery
Example:
if (Request.Browser.Cookies)
{
Response.Write("Welcome To Hello World Cookies Accepted by the browser");
}
else
{
Response.Write("Good Bye To Hello World. Cookie diabled in your browser. Enable cookies and Try again... Cool..");
}

session lost on redirect

I have a web app that is being hit by facebook. The login page retrieves the keys that I need and sets some session variables. When the server then redirects the user to the next page, the session information is lost. I’m running the IIS engine on vista ultimate at the moment, the app pools don’t matter because I’m using a state service and I’m still losing the session state. I’ve tried both the overloaded method of the response.redirect function and also adding a header to the page to force the redirect and none of this seems to work. Does anyone have any ideas of what I’m missing?
I’ve tried both of these:
Response.Headers.Add("refresh", "3;url=Dashboard.aspx")
And
Response.Redirect("Dashboard.aspx", False)
[EDIT]
So i just did a little experiment and well it turns out that when I hit the url directly from the facebook page I get the problem, but when i copy the url for the IFrame into a new browser window and try it it works fine.
[EDIT]
So I found an article on this and after addin gthe header the problem was solved (for now)
http://support.microsoft.com/kb/323752
Response.AddHeader("P3P: CP", "CAO PSA OUR")
when I hit the url directly from the facebook page I get the problem, but when i copy the url for the IFrame into a new browser window and try it it works fine.
If you're in an iframe, any cookies you set are “third-party cookies”. Third-party cookies may be subject to more stringent conditions than the normal “first-party” cookies you are setting when the user is directly on your site. This can be due to different browser default cookie handling or because the user has deliberately configured it like that. (And for good reason: many third-parties are unpleasant privacy-invading advertisers.)
In particular, in IE6+ with the default settings, you cannot set a third-party cookie unless you write a P3P policy promising that you will be a good boy and not flog your users' data to the nearest identify thief.
(In practice of course P3P is a dead loss, since there's nothing stopping the site owner from just lying. Another worthless complication that provides no actual security. Yay.)
I'd try running Fiddler and see if your session cookie is being sent properly with the response when interacting with your app via Facebook.
The session depends also on cookie support by the client. When you say the app "is being hit by facebook" are you sure that by what ever means they are "hitting" you they are supporting cookies?
Response.Redirect and refresh don't carry session. Server.Transfer() can but loses the ability to transfer to other servers/sites.

ASP.NET application exhibits strange behaviour through firewall

This problem has been solved thanks to your suggestions. See the bottom for details. Thanks very much for your help!
Our ASP.NET website is accessed from several specific and highly secure international locations. It has been operating fine, but we have added another client location which is exhibiting very strange behaviour.
In particular, when the user enters search criteria and clicks the search button the result list returns empty. It doesn't even show the '0 results returned' text, so it is as if the Repeater control did not bind at all. Similar behaviour appears in some, but not all, other parts of the site. The user is able to log in to the site fine and their profile information is displayed.
I have logged in to the site locally using exactly the same credentials as them and the site works well from here. We have gone through the steps carefully so I am confident it is not a user issue.
I bind the search results in the Page_Load of the search results page the first time it is loaded (the criteria is in the query string). i.e.
if (!IsPostBack) {
BindResults();
}
I can replicate exactly the same behaviour locally by commenting out the BindResults() method call.
Does anybody know how the value of IsPostBack is calculated? Is it possible that their highly-secure firewall setup would cause IsPostBack to always return true, even when it is a redirect from another page? That could be a red herring as the problem might be elsewhere. It does exactly replicate the result though.
I have no access to the site, so troubleshooting is restricted to giving them instructions and asking for them to tell me the result.
Thanks for your time!
Appended info: Client is behind a Microsoft ISA 2006 firewall running default rules. The site has been added to the Internet Explorer trusted sites list and tried in FireFox and Google Chrome, all with the same result.
SOLUTION: The winner for me was the suggestion to use Fiddler. What an excellent tool that no web developer should be without. Using this I was able to strip various headers from the request until I reproduced the problem. There were actually two factors that caused this bug, as is so often the case with such confusing issues.
Factor one – Where possible the web application uses GZIP compression as supported by all major browsers. The firewall was stripping off the header that specifies GZIP decompression support (Accept-Encoding: gzip, deflate).
Factor two – A bug in my code meant that some processing was bypassed when the content was being sent uncompressed. This problem was not noticed before because the application is used by a limited audience, all of which supported GZIP decompression.
If they're at all tech-savvy, I would have them download Fiddler or something similar, capture the entire HTTP session, and then send you the saved session. Maybe something in there will stick out.
Meanwhile, see if you can get an install of ISA Server (an evaluation install, if you have to, or one from MSDN if you have or know anyone with a sub) and see if you can replicate it locally.
Is it possible the client has disabled Javascript and it's not picking up the _EVENTTARGET form value?
It might be some sort of proxy which creates a GET request out of a given POST request...
I am not sure how the IsPostBack is calculated, but my guess would be that it checks the HTTP request to see if it's a POST or a GET...
Ohh, yeah. It's definitely NOT "_EVENTTARGET" BTW...
I know this since Ra-Ajax does NOT pass any of those parameters to the server and they (Ra-ajax requests) are processed as IsPostBack requests...
Location, location, location. Check the user's culture. Normally that causes issues.
Could you create a test Post Page that passes the same things that your search page does, and in the Page_Load write back all of the post to make sure they are getting passed, particularly the __VIEWSTATE.
foreach (string key in Request.Form)
{
Response.Write("<br>" + key + "=" + Request.Form[key]);
}
Then ask one of the users to forward back what they see on that test page.
EDIT: There is documentation that some firewalls can corrupt the VIEWSTATE and some methods to get around it: View State Overview
Check the IIS logs to see if the request even makes it to your server. The ISA setup might be caching the initial request and serving that up in the succeeding requests.

Resources