HttpCookie Is Not Deleted When Session Changes Or Is Invalid?
Jul 20, 2010
I'm creating an HttpCookie, setting only the name and value and not the expires property, then adding it to the response. Simple enough. The cookie is created (but not persisted) as expected. The problem is when the session changes for some reason (like the website was rebuilt, or I rebuilt my app when debugging) then the cookie stays around. I want the cookie to be valid for only the original session it was created on.
According to MSDN it says: "If you do not specify an expiration limit for the cookie, the cookie is not persisted to the client computer and it expires when the user session expires." I guess I don't know exactly what "session expires" encompasses. I figure the cookie gets deleted after 20 min when the session expires. But should the cookie get deleted if the session it was created on doesn't exist anymore for any number of reasons? The only time I've seen the cookie get deleted is when the user closes all browser windows and opens a new one.
If this is all true, I may have to store the original session id ("ASP.NET_SessionId") in the cookie, then check it against the current session id, if they're different, then delete the cookie or create a new one.
Here's the code (the only difference between my cookie and the one in the MSDN examples is I'm storing multiple values in the cookie):
private void SaveValuesToCookie(string[] names, string[] values)
{
HttpCookie cookie = new HttpCookie("MyCookie");
for (int i = 0; i < names.Length; i++)
{
string name = names[i];
cookie.Values[name] = values[i];
}
Response.Cookies.Add(cookie);
}
private string GetValueFromCookie(string name)
{
HttpCookie cookie = Request.Cookies["MyCookie"];
if (cookie == null)
return null;
return cookie.Values[name];
}
When i press the delete button, everything works fine and the folder gets deleted. but after that when page postbacks again then a NullRefrenceException is raised at Label1.Text = Session["loginid"].ToString(); why is it happening...?? When I am not using this Directory.Delete() method everything is working fine and session variables are not set to null. When I traced my application I found that After Directory.Delete() method Session variables were intact and I was able to use those session variables in the processing after Directory.Delete(). But as soon as the page postbacks all session variables are set to null. And this problem doesn't appear when i m not using this delete() method. The folder I m deleting is in my project's folder. I m running this website using Visual Studio.
I have an ASP.NET 2.0 site that stores a user's ID in session to indicate that they are logged in. In some situations, the user doesn't appear to stay logged in. I've been monitoring traffic in Fiddler, and some details I've found: The problem is 100% repeatable on an older laptop of mine when running IE7 and the project manager's laptop when running IE7. The problem does not ever occur on my current laptop running IE7, or any of these laptops when running FF. The problem occurs only in production--not on development, internal staging, or client staging. Production is the only load balanced environment, but the repeatability noted above makes me question load balancing as a factor.
When the page which sets Session("ID") = 1 sends a response back to the client, I can see a "Set-Cookie" header in all cases, which is creating the ASP.Net_Session_Id cookie (and it's HttpOnly). Subsequent requests to the server will send that cookie in the header on machines which are not exhibiting the problem, but not on machines that are, so either the cookie is getting deleted or the "Set-Cookie" header is being ignored.
The way logging in works is as follows: a page on [URL] has an iframe. The source of that iframe is a page on [URL]. A variety of pages served from [URL] take the user through the login/register process. The final step of [URL] is to redirect to a page back on [URL], including the user's ID in the querystring. This page on [URL] typically stores the ID in session, and then runs some JS to redirect the top level document to a new page, thus taking the user out of the iframe. This is a process that has worked for several years, with several values of [URL]. The one thing that may be different here is that in this case, the JS is simply destroying the iframe and some containing div's.
Another difference I see between scenarios where the problem occurs and where it doesn't is in the Google Analytics cookies. There is a difference when [URL] does its redirect to [URL] inside the iframe. When the problem does not occur, the request for SaveTheID.aspx includes a variety of Google Analytics cookies (__utma, __utmz, etc). When the problem does occur, this request does not include all the GA cookies (it's missing __utma, __utmz and __utmb). Production is the only environment where [URL] runs under SSL, so I thought that may be related. But we temporarily set up our staging copy of [URL] to use SSL, and that had no effect.
System.InvalidCastException was unhandled by user code
Message=Specified cast is not valid.
Source=App_Web_donate.aspx.cdcab7d2.wqdohvu3 StackTrace: at Donate.LoadUserDetails() in C:UsersSimonDesktopLocal SitesCats ProtectionNewDonate.aspx.vb:line 261 at Donate.btnDonate30_Click(Object sender, EventArgs e) in C:UsersSimonDesktopLocal SitesCats ProtectionNewDonate.aspx.vb:line 205 at System.Web.UI.WebControls.LinkButton.OnClick(EventArgs e) at System.Web.UI.WebControls.LinkButton.RaisePostBackEvent(String eventArgument) at System.Web.UI.WebControls.LinkButton.System.Web.UI.IPostBackEventHandler.RaisePostBackEvent(String eventArgument) at System.Web.UI.Page.RaisePostBackEvent(IPostBackEventHandler sourceControl, String eventArgument) at System.Web.UI.Page.RaisePostBackEvent(NameValueCollection postData) at System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint)
InnerException: I have made the important bits Bold I have the following code which is generating this error:
[Code]....
I am not entirely sure what is causing it. Its completley intermitent. I am storing all the details of a user filling in a form in a structure, and then assigning that structure to a session variable. This means if they page back, and then page forward again, I can pre-populate the form with the details they have already filled in for their conveinience by using the above code snippet. It appears that it works for a good minute, but if I leave the browser alone any longer than roughly 60 seconds, and then try and page forward to the form again, the exception will fire. While writing this post, the exception has occured in again in firefox, but interestingly, Google Chrome doesn't seem to have this problem. It looks like I can leave chrome alone for as long as I want and it will still work.
I am creating some cookies in my ASP.NET application. These cookies expire 10 minutes after they have been created. I follow the approach described on MSDN as shown here:[URL]
My question is, when a cookie "expires", what happens? Does the browser automatically delete the cookie? Is it our responsibility as developers to remove the cookies if they exist and have expired?
A web site was developed and deployed to client. In some cases, I need to set the flag HttpCookie.HttpOnly = true. Okay - I have done it. Next question:
Is Cookie available after setting flag in JavaScript? or maybe some restriction when I am using JavaScript? or do I need to make some changes in existing JavaScript?
I'm trying to write cookies from my website and I'm trying to figure out what implications timezones has over the HttpCookie.Expire property. Should I be passing DateTime.Now.AddDays(1) or DateTime.UtcNow.AddDays(1) or the users's timezone plus a day?
I have a web application developed using VB .Net 2003, and is running ASP Net 1.1.
The application is running fine on all browser, except for the login/authentication control that doesn't work properly on Chrome.
We have different types of users using the website, and each user type has different menu items displayed for.
The problem is, if a user logs on with let's say Admin account, and logs off and later logs on again using student account, the user still gets the Admin menu, and of course vice versa.
I'm not sure if I'm doing something wrong, or there is something I'm missing here.
On more thing, if the timeout period reached, and the session was timed out , and the user (regardless of the type) tries to log on again, he is successful on all browser except on Chrome again!, where it keeps telling the session was timed out, and never logs on again until clearing the cookies.
This has been a nagging issue for some time, but very sporadic and difficult to isolate.
From time to time, browsers that have authenticated on a web application, have been open for a while, have logged in and out of the same web application multiple times, have multiple tabs, are pretty much any browser (Chrome, IE, Firefox, Safari), and seemingly at random, lose their ability to retain an AuthCookie after being set and followed by a redirect. Closing the browser and starting a new session resolves the issue, as does opening up a different browser and attempting to authenticate.
Our team uses forms authentication for all of our websites and web application. This is a pretty typical setup where a login form is displayed, the user enters credentials and a cookie is set on the click event of the postback, then a redirect occurs to the same page where the cookie is then referenced and used to complete authentication.
In this situation
FormsAuthentication.FormsCookieName = ".WebAuth"
Within Event:
FormsAuthenticationTicket authTicket = new FormsAuthenticationTicket(1, Username, DateTime.Now, DateTime.Now.AddMinutes(SessionTimeout), false, Username); HttpCookie faCookie = new HttpCookie(FormsAuthentication.FormsCookieName, FormsAuthentication.Encrypt(authTicket)); Response.Cookies.Add(faCookie); Response.Redirect(Request.RawUrl, true); After the redirect, on PreInit: HttpCookie authCookie = Request.Cookies[cookieName];
At this point, the authCookie variable is typically not null, but in these isolated circumstances that I've outlined above, the cookie comes back null after the redirect.
This happens very randomly, sometimes weeks before affecting one of our developers. As I said, restarting the browser resolves the issue.
Today I had it happen on our dev server while using Chrome. I had logged into the application, allowed the application to session timeout, and then attempted to login again. The attempted login then failed to set the cookie. I remotely attached Visual Studio to the process on the server to begin debugging. The entire time I could step through my code, even deploy new code versions to the server with updates, restart the app, restart IIS on the server, attach and reattach to the project, and the issue persisted in Chrome. In Firefox, I was able to authenticate without issue.
From Chrome, the login would validate, attempt to set a Response Cookie as outlined above. Prior to redirect, I could see the properly set Response Cookie, as well as its counterpart in the Request Cookies. However, on each redirect after a seemingly successful login, the Response and Request Cookie are gone.
I enabled Trace on the application to view the cookie collection:
There is a .WebAuth in the Request Cookies Collection, as well as ASP.NET_SessionId and several ASPSESSIONIDxxxxxxxx, but when the page loads, only the ASP.NET_SessionId and ASPSESSIONIDxxxxxxxx cookies are available in the Request.Cookies scope, no sign of the .WebAuth. However, in the page's Trace information after render, there multiple .WebAuth cookies listed, it is just that the page seems to have no access to them.
Primarily, on a working version after authentication there is both a .WebAuth Response and Request Cookie in the page's Trace info. But on a non functioning browser window, the Response Cookie is absent.
Has anyone else had any experience with this? It is such a nagging issue, and so sporadic, but I would love to be able to resolve it. My concern is that it may be affecting users and we would have no knowledge since the description of the issue is so convoluted.
I have a site that is using Forms Auth. The client does not want the site session to expire at all for users. In the login page codebehind, the following code is used:
// user passed validation FormsAuthentication.Initialize(); // grab the user's roles out of the database String strRole = AssignRoles(UserName.Text); // creates forms auth ticket with expiration date of 100 years from now and make it persistent FormsAuthenticationTicket fat = new FormsAuthenticationTicket(1, UserName.Text, DateTime.Now, DateTime.Now.AddYears(100), true, strRole, FormsAuthentication.FormsCookiePath); // create a cookie and throw the ticket in there, set expiration date to 100 years from now HttpCookie cookie = new HttpCookie(FormsAuthentication.FormsCookieName, FormsAuthentication.Encrypt(fat)) { Expires = DateTime.Now.AddYears(100) }; // add the cookie to the response queue Response.Cookies.Add(cookie); Response.Redirect(FormsAuthentication.GetRedirectUrl(UserName.Text, false));
When I log into the site I do see the cookie correctly being sent to the browser and passed back up: However, when I walk away for 20 minutes or so, come back and try to do anything on the site, the login window reappears. This solution was working for a while on our servers - now it's back. The problem doesn't occur on my local dev box running Cassini in VS2008.
Doing some work with Facebook connect/the RESTful API and for some reason i keep getting this error
Session key invalid or no longer valid As far as i can tell im authenticating correctly. Getting the session key from the cookie after the facebook connect dialog pops up and the user logs in. Then i open up the extended permissions dialog to allow posting events and offline access. But then if the user was to logout of facebook the session key becomes unusable. What am i doing wrong here? Is there any good examples of doing this with ASP.NET/C#?
I am getting this error "The session state information is invalid and might be corrupted " as i hve checked all my session variable initialized with some default value and the existing code works fine in version 1.1 but on conversion it is giving specified error. The error comes when i simply click on a link to redirect to some other page.
I have a FormView through which I set up the default new, update and delete commands for communicating with an SQL Server database. When the CREATE command is executed the data is added to the database and some images are uploaded to a server and linked to the database.
When I press the Visual Studio's default FormView DELETE command I obviously only delete the selected row in the database and not the images on the server. I marked the uploaded images with images ID + "name" , so I could delete them if I could only retrieve the ID of the row being deleted by the DELETE command. How do I do retrieve the ID of the deleted row in C#?
I want to delete one file, e.g. Foo1.aspx, then rename another, Foo2.aspx, as Foo1.aspx. However, even after the deletion, I can't rename Foo2.aspx, presumably because TFS keeps around the original for recovery purposes.
Is there a way to do this, other than selecting the contents of Foo2. aspx and pasting it into Foo1.aspx?
my requirement is to delete database value automatically on a given date. In my application i am inserting records in database, now admin will give the expiration date for the value inserted in db. On that particular date, the value should be deleted automatically. I want a logic for this in asp.net. I am using SQL 2005 with C#.
I am passing a file name via query string. When I am trying to delete the file it is throwing a FileNotFoundException. But the file practically deleted from the server. Both of the following codes of file delete :
[Code]....
are throwing that exception.Can any one please tell me what is the reason behind this behavior or what I am doing wrong?
i want to delete a file present in directory on the server. I have tried following code but code inside the file.exist never runs. It always skips it showing me that file does not exist. But file is present.
in sql server 2005, i have deleted row by mistake and now want to roolback them, i wrote a query is "delete tblmetric" nd pressed F5 now wanna to recover the rows
I have a ASP.NET application, but whenever I run the application in a web browser, any .master page or XML page getes deleted automatically. I've tried everything I can but it keeps happening when using IIS 7 in Server 2008. This does not happen on IIS6/Server 2003.
Where LK_URL is pointing to a file in the PDFs folder. In this case I have connected to the server and removed a particular PDF but the link still works. I have deleted all my cache (internet tools - temp files delete all) but it still works. This has come about because someone made a change to a PDF, I uploaded it overriding the original. I see the new one on my PC but he still see's the original.
I have a code which creates an image in application server and that image has been referred in mail html. After sending mail, image will be deleted in application server. When i open the mail , image is not getting display in the mail.
The reason i guess is , my code is deleting the image before it copied to mail server. I have checked by deleting the image manually.
First i opened the mail(this time image get copied to mail server) and then deleted the image in pplication server. When i open the mail 2nd time, image get display(because image is in mail server i guess)
Again i ran the code, this time before opening mail first time, i deleted the image in application server and opened the mail. Image is not displaying(because image not getting copied to mail server).