Session values are lost between calls - asp.net

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!!

Related

Why do all ASP.NET MVC websites allow and ignore the string "/(F())/" in front of ANY URL?

I noticed that requests to my ASP.NET web app succeed even if I prefix the URL with /(F())/ which is nonsense. The usual action method is hit. Request.Url does not show the URL prefix. So if I request /(F())/x the action sees Request.Url == "/x"
I then tried other ASP.NET MVC sites such as Stack Overflow:
https://stackoverflow.com/(F())/questions/43593952/why-do-all-asp-net-mvc-websites-allow-and-ignore-the-string-f-in-front-o
According to Fiddler the request is being made as intended:
As you can see the request URL is correct and the server replies without redirect with the full content. The browser window shows that URL as well.
This URL does work. So I conclude that something in the framework causes this request to be rewritten and the prefix dropped. It looks like the Stack Overflow application was unaware of the prefix.
The same result occurs in a fresh MVC app created in Visual Studio 2017 on .NET 4.6.2 on Windows 7.
Another funny victim: https://www.microsoft.com/(F(blah))/en-us/default.aspx (The Microsoft homepage).
The string (F()) is not special. See the comments for other strings that work e.g. /(F(pV0)).
Since my ASP.NET code is blind to the original URL (Request.Url does not contain the prefix) I seemingly cannot even detect this condition and fail the request.
I have not confirmed that this is an MVC problem. It seems hard to find the culprit in the huge sea of functionality that ASP.NET+IIS ship with. Who knows what features are turned on by default?! I don't think anyone really knows :)
At the very least this is an SEO problem but I find it disturbing as well to not know what's going on. That's why I'm investigating. What behavior is that and how to get rid of it?
This is caused by the ASP.NET cookieless feature set. The URL may now look like this:
http://example.com/MyWebApplication/(A(XXXX)S(XXXX)F(XXXX))/home.aspx
Breaking it down:
A(XXXX): This is the Anonymous-ID. It is used to identify the (anonymous) user accessing your application. The string may or may-not be encrypted, depending on your configuration settings in the section.
S(XXXX): This is the Session-ID (same as V1.1).
F(XXXX): This is the Forms Authentication ticket.
Since cookieless mode is entirely obsolete, causes SEO problems and confusion I recommend to disable all possible cookieless features on all ASP.NET websites immediately.
For each of the above features (Forms Authentication, Anonymous Identification, and Session State), you can control if and when the cookiesless feature will be used, and when the cookieless feature will be used instead. The configuration setting controlling this is:
cookieless="UseCookies | UseUri | UseDeviceProfile | AutoDetect"
In my case I set:
<anonymousIdentification enabled="false" />
<sessionState ... cookieless="UseCookies" />
You will need to adapt this to your needs.
This hopefully addresses the generation of these URLs but seemingly it does not prevent the framework from (silently) accepting such a URL. The documentation claims that a header AspFilterSessionId will be present but I found that not to be the case.
For now I have no solution for blocking requests to these unwanted URLs.

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

ASP MVC - Bunch of random characters in POST request route string

I am trying to log in to my own application, and i have discovered something strange. When I am sending a POST request to a login controller, it somehow redirects itself to a GET login controller, and displays login form with an action set to http://localhost:5898/(X(1)S(1tgv3m2psb2cxqaw4koiyhyt))/Account/Login. Now what the hell is this (X(1)S(1tgv3m2psb2cxqaw4koiyhyt)) thing? Why is it there, and what does it do? And on top of that, how do i get rid of it? I do not want it in there...
It appears that you have set the session provider in your web.config (or on IIS) to use a Cookieless session state. This is the session identifier for your session.
http://msdn.microsoft.com/en-us/library/aa479314.aspx#cookieless_topic2
To get rid of it, you would need to change your sessionState element in your web.config to cookieless="false"
SessionState Web.Config element information
Those things are seen in asp.net when you disable cookie in your browser or your application settings. that is cookieless asp.net. you can start debugging your app from there.
hope it helps

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.

Session.Start called on every request when fired

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.

Resources