I searched here on the stackoverflow about removing all cookies from site, but couldn't find a single answer suggesting the use of Request.Cookies.Clear() method.
What's the difference between:
if (Request.Cookies["UserSettings"] != null)
{
HttpCookie myCookie = new HttpCookie("UserSettings");
myCookie.Expires = DateTime.Now.AddDays(-1d);
Response.Cookies.Add(myCookie);
}
and:
Request.Cookies.Clear();
Thanks in advance!
and sorry for my bad language, English is not my native!
Calling Remove or Clear will remove it from the server side collection held by Request.Cookies (which is a copy of the cookies your client sent to you). However that does not cause the server to instruct the client browser to remove the cookie. To do that you need to set the timeout as you have indicated above (see MSDN - How To: Delete a Cookie for the official guidance).
Related
I am putting a a "try it out" function on the front page of my site - basically a visitor can try a very limited set of what my site does, in browser, to see what it's all about.
I want to put a persistent cookie in to check if they've tried it out before, and if so direct them to the sign up page instead (I'm aware this isn't foolproof, but I'm not looking for Fort Knox, anyone looking to avoid that check will never sign up anyway, I'm just trying to nudge people who have liked the functionality to maybe sign up.)
When the user clicks the try it out button, my code is:
//check cookie to see if this has been tried before
HttpCookie myCookie = HttpContext.Current.Request.Cookies["myCookie"];
if (myCookie == null)
{
generateLink()
}
else {
response.Redirect(~/SignUp);
}
and at the end of the generateLink() method I have the code:
HttpCookie myCookie = new HttpCookie("myCookie");
myCookie.Values.Add("HasTried", "True");
myCookie.Expires = DateTime.Now.AddHours(9680);
but the "try it out" button always generates a Link, and never fires the respone.redirect. Where am I going wrong?
You need to add the cookie to the response:
Response.Cookies.Add(myCookie);
If you place that at the end of the code from generateLink() that'll write the cookie to browser.
See:
How to write a cookie, from MSDN.
Response.Cookies.Add(myCookie);
is missing at the end
I'm trying to remove cookies using C# when a user logs out. The code suggestions listed here: remove cookies from browser do not work. I put several of them together in desperation and they are not working.
if (Request.Cookies["loginidcookie"] != null)
{
HttpCookie myCookie = new HttpCookie("loginidcookie");
myCookie.Value = String.Empty;
myCookie.Expires = DateTime.Now.AddDays(-1d);
Response.Cookies.Add(myCookie);
Response.Cookies.Remove("loginidcookie");
}
Response.Redirect("logout.aspx");
So not only am I overwriting the value of the cookie with an empty string, I am setting it to expire yesterday AND removing it from the list of cookies. Yet when I run this code then hit the back button and reload, the cookie is still there with its original value. So how do I get rid of it?
Thank you
Try this instead:
string cookieName = "loginidcookie";
if (Request.Cookies[cookieName ] != null)
{
var myCookie = new HttpCookie(cookieName);
myCookie.Expires = DateTime.Now.AddDays(-1d);
Response.Cookies.Add(myCookie);
}
Response.Redirect("logout.aspx", false);
Note (from here):
You cannot directly delete a cookie on a user's computer. However, you
can direct the user's browser to delete the cookie by setting the
cookie's expiration date to a past date. The next time a user makes a
request to a page within the domain or path that set the cookie, the
browser will determine that the cookie has expired and remove it.
You are adding the Cookie and then Removing it from the collection before the response is sent so you are effectively doing nothing.
HttpCookie myCookie = new HttpCookie("loginidcookie");
... and then below
Response.Cookies.Add(myCookie);
Response.Cookies.Remove("loginidcookie");
If you change the cookie to expire yesterday, you need to leave the cookie in the collection so that the browser takes care of deleting it once it sees the cookie has been updated with an expiration date in the past. In other words, don't call Response.Cookies.Remove("loginidcookie");
Try RedFilter's solution but use Server.Transfer() or Server.TransferRequest() instead of Response.Redirect() which it seems doesn't always let those cookie responses happen due to a possible bug.
Are you checking the cookie after closing the browser? Or reloading the page in the same browser?
If you are opening the page in the same browser you will see the cookie which is expired, but if you opened the new browser and try to access the page again, you would not get the cookie.
The website where I work is made up of several projects (written in several languages). Right now we have to use some awkward code in query strings and session variables to keep a person logged in when they go from project to project. Since cookies are domain specific we're trying to convert to them since they can be set in one project using one language yet be accessed by a different project (on the same domain) using a different language.
However I am having problems changing the value of a cookie and deleting them. Or to be more specific, I'm having trouble having any changes I make to a cookie stick.
For example in my logout code:
if (Request.Cookies["thisuserlogin"] != null)
{
HttpCookie myCookie = new HttpCookie("thisuserlogin");
myCookie.Value = String.Empty;
myCookie.Expires = DateTime.Now.AddDays(-1d);
Response.Cookies.Add(myCookie);
Response.Cookies.Set(myCookie);
litTest.Text = myCookie.Expires.ToString() + "<br />" + Request.Cookies["thisuserlogin"].Expires.ToString();
}
I wind up with one line being yesterday and the next line being 1/1/0001 12:00:00 even though they SHOULD be the same cookie. So why is it that even though the cookie was set, it's value did not change? Is there a way to force the user's computer to update a cookie's value, including deletion?
Thank you very much.
PS Any URLs you can provide to give an easy-to-understand primer for cookies would be appreciated.
http://msdn.microsoft.com/en-us/library/ms178194(v=vs.100).aspx
if (Request.Cookies["thisuserlogin"] != null)
{
HttpCookie byeCookie = new HttpCookie("thisuserlogin");
byeCookie.Expires = DateTime.Now.AddDays(-1);
Response.Cookies.Add(byeCookie);
// Update Client
Response.Redirect(Request.RawUrl);
}
You should use a tool like Fiddler on the client side to capture all of the data going back and forth. This will help you see that your cookie should be set with a date in the past (and missing from the next request too).
As for your textbox output, you're listing the cookie you created expire time and the expire time of the request cookie, which doesn't have one. If you were to look at the response cookie instead, you should see the date being set. Also, the call to Response.Cookies.Set is unnecessary. Response.Cookies.Add should be all you need.
Client has a site at a.url.com. Client creates a cookie with host as ".url.com" and path as "/". Client redirects to us at b.url.com. Client has a coding issue that requires us to delete the cookie (long story).
The following code is not adjusting the expiration at all in our test or production environments but is working fine locally.
if (Request.Cookies["cookie"] != null)
{
HttpCookie myCookie = new HttpCookie("cookie");
myCookie.Expires = DateTime.Now.AddDays(-1d);
Response.Cookies.Add(myCookie);
}
Any ideas?
We've figured it out. We needed to add one line of code to manually set the domain. Makes total sense now.
if (Request.Cookies["cookie"] != null)
{
HttpCookie myCookie = new HttpCookie("cookie");
myCookie.Domain = ".url.com";
myCookie.Expires = DateTime.Now.AddDays(-1d);
Response.Cookies.Add(myCookie);
}
is this a third party cookie? If so, the default security settings in IE will prevent cookie writing in the "internet" zone but it is allowed in your local zone.
Here's a hack. I am just posting this in case you find out that you cannot do what you want due to some security issue preventing you handling the issue on the second site.
You could send a request to the first site to clear the cookie via redirect and have that site bounce the user back again. Like I said, this is very hackish (or I suppose marketing would call it inter-site cooperative security feature).
Hopefully, there's a better approach, but at least you have an alternative if no other ones are forthcoming.
If you cannot get it working in C# you might want to consider seeing if you can manipulate the cookies in javascript.
Gary
I have the following code that sets a cookie:
string locale = ((DropDownList)this.LoginUser.FindControl("locale")).SelectedValue;
HttpCookie cookie = new HttpCookie("localization",locale);
cookie.Expires= DateTime.Now.AddYears(1);
Response.Cookies.Set(cookie);
However, when I try to read the cookie, the Value is Null. The cookie exists. I never get past the following if check:
if (Request.Cookies["localization"] != null && !string.IsNullOrEmpty(Request.Cookies["localization"].Value))
Help?
The check is done after a post back? If so you should read the cookie from the Request collection instead.
The cookies are persisted to the browser by adding them to Response.Cookies and are read back from Request.Cookies.
The cookies added to Response can be read only if the page is on the same request.
The most likely answer is seen on this post
When you try to check existence of a cookie using Response object rather than Reqest, ASP.net automatically creates a cookie.
Edit: As a note, I ended up writing software that needed to check the existence of cookies that ASP.NET makes a nightmare due to their cookie API. I ended up writing a conversion process that takes cookies from the request and makes my state object. At the end of the request I then translate my state object back to cookies and stuff them in the response (if needed). This alleviated trying to figure out if cookies are in the response, to update them instead, avoiding creating of pointless cookies etc.
Have you tired "Request" collection instead of "Response" collection?
if (Request.Cookies["localization"] != null && !string.IsNullOrEmpty(Request.Cookies["localization"].Value))
I had a similar problem, I couldn't read cookies on postback. The issue for me was that I checked the Secure property of the cookie to true. It is said that when the Secure property of the cookie is turned on, it causes the cookie to be transmitted only if the connection uses the Secure Sockets Layer. I am not sure, however, how I was able to see the cookie in the browser the first time, but not on postback, considering that I wasn't transmitting over SSL. Anyhow, turning the cookie.Secure to false, solved the problem, and had cookies read on postback.
Sorry if this doesn't have to do anything with your issue, I wanted to share this, because I spent some time looking how to resolve this.
I think I know the answer.
Just REMOVE the action attribute in your <form> tag.
make it look like this: <form id="form1" runat="server">
instead of this: <form id="form1" action="DisplayName.aspx" runat="server">
You should then use Response.Redirect("DisplayName.aspx"); in your code.
if you're compiling in debug mode, turn on tracing for the pages in question and make sure the cookie is in the request collection. Set trace in the #page directive in the aspx file.
Try this snippet -
string locale = ((DropDownList)this.LoginUser.FindControl("locale"))
.SelectedValue;
HttpCookie myCookie = new HttpCookie("localization");
Response.Cookies.Add(myCookie);
myCookie.Values.Add("locale", locale);
Response.Cookies["localization"].Expires = DateTime.Now.AddYears(1);
& to read it -
if (Request.Cookies["localization"] != null)
{
HttpCookie cookie = Request.Cookies["localization"];
string locale = cookie.Values["locale"].ToString();
}
Would add this as a comment to Chris Marisic's answer but I don't have that privelage :-(
Further to what Chris said in his edit about removing cookies from the request, to be able to read the newly created cookies value in a postback I ended up doing
Private Sub SetPageSize(ByVal pageSize As Integer)
' Set cookie value to pageSize
Dim pageSizeCookie As HttpCookie = New HttpCookie(pageSizeCookieName)
With pageSizeCookie
.Expires = Now.AddYears(100)
.Value = pageSize.ToString
End With
' Add to response to save it
Me.Response.Cookies.Add(pageSizeCookie)
' Add to request so available for postback
Me.Request.Cookies.Remove(pageSizeCookieName)
Me.Request.Cookies.Add(pageSizeCookie)
End Sub
The Request.Cookies.Remove and Request.Cookies.Add lines making it work on postbacks
use Response.Cookies.Add(cookie); instead of Response.Cookies.Set(cookie);