I have two sites set up on one Windows 2008 IIS server. On the first site, the user hits the web page and the following simple C# code is used to create a cookie.
<%
HttpCookie myCookie = new HttpCookie("MyTestCookie");
myCookie.Value = "Hi";
myCookie.Expires = DateTime.Now.AddMinutes(1);
Response.Cookies.Add(myCookie);
>%
I've verified that this site can in fact "see" the cookie and I can use the following code to display its value:
<% Response.Write(Request.Cookies["MyTestCookie"].Value); %>
On the other site hosted on the exact same server. I use the following code to see if the cookie is assigned a value:
if (Request.Cookies["MyTestCookie"] == null)
{
lblErr.Text = "Cookie is null.";
}
else
{
lblErr.Text = Request.Cookies["MyTestCookie"].Value;
}
It's null. Just a few days before, however, it wasn't null. In the full code of the actual site, it was working for all but a few users. In trying to troubleshoot these particular users, it stopped working for everyone.
I don't know what I'm doing wrong, but I need to pass values between two sites which are completely independent and unaware of each other. I thought first-party cookies work fine if on the same server. What am I doing wrong?
Cookies are associated with the URL they come from - the browser would not send to site B the cookies received from site A (and vice-versa).
EDIT
If the problem is user-dependant maybe it is related to the cookie settings in the browser - if some user are blocking cookies for example.
Try setting the Path property to "/" and make sure the sites share the same domain name.
If they are on different sub domains, set the Domain property to domainname.com (your domain name).
Edit:
Your code should look like this:
if (Request.Cookies["MyTestCookie"] == null)
{
HttpCookie myCookie = new HttpCookie("MyTestCookie");
myCookie.Path = "/";
myCookie.Domain = "domain.com";
myCookie.Value = "Hi";
myCookie.Expires = DateTime.Now.AddMinutes(1);
Response.Cookies.Add(myCookie);
lblErr.Text = "Cookie was null.";
}
else
{
lblErr.Text = Request.Cookies["MyTestCookie"].Value;
}
The expiry time you set for the cookie (one minute from now) is a bit too short. Try setting it to 6 months in the future and see if that helps.
Related
I want to set cookies for a specific domain to fetch data in English version in C# while crawling the website. Suppose a website www.xyz.com has four language version including English. The actual data in database are in any other language (suppose Swedish). While crawling the site to get all of its links and text, need to fetch the contents of English version. That's why I want to set cookies there. But it's not working. Please check the piece of code below to set cookie for English version.
if (_domain == "www.xyz.com")
{
HttpCookie CreateLangCookie()
{
HttpCookie cookie = new HttpCookie("Cookies");
cookie.Name = "lang";
cookie.Value = "en";
cookie.Domain = ".xyz.com";
cookie.Path = "/";
cookie.Expires = DateTime.MaxValue;
return cookie;
}
Response.Cookies.Add(CreateLangCookie());
}
You might want to expand your question to note what you mean by "not working" and to include what browser you are using, but the solution might be to not use explicit cookies, as explained in this answer: Cookies with and without the Domain Specified (browser inconsistency)
How to delete cookies in ASP.NET after changing machine key but staying on the same sub-domain?
Currently we have cookies on example.domain.com, but we need to move to wildcard cookies (.domain.com) so that the cookie also work on foo.domain.com. In order to do this, we have manually set a machine key to encrypt/decrypt the asp.net login cookie. Problem is that people that already have the old cookie, will now receive a CryptographicException when trying to access the site (as it tries for some reason to decrypt the old cookie). We have changed the name of the cookie, but it did not help - still receives the error. So we figured out that we wanted to delete all the old cookies. We try do do this on the login site with the following code:
var myCookies = Request.Cookies.AllKeys;
foreach (var cookieName in myCookies)
{
var cookie = Request.Cookies[cookieName];
if (cookie == null) continue;
cookie.Value = "written " + DateTime.Now;
cookie.Expires = DateTime.Now.AddYears(-1);
cookie.Domain = "example.domain.com"
Response.Cookies.Add(cookie);
}
We reach the code, and it runs, but the cookies still remain when inspecting in google chrome resources. So obviously the deletion did not work. We have tried several different ways (adding path ="/", setting cookie.Value to cookie.Value etc. For some strange reason the cookies still remain and we are unavailable to delete them.
So to get back to the original question, how an we delete cookies in ASP.NET MVC 4.5 after changing to a wildcard domain on our cookies and explcitly stating the machine key in the web.config?
If you don't absolutely have to use the same ticket name, your solution should work if you changed the name of the FormsAuthentication cookie:
<forms name=".YOUR_NEW_COOKIE_NAME" /> **
** Note that I've omitted the other attributes from the tag shown, so you wouldn't want to copy/paste it verbatim.
Turns out that by removing cookie.Domain, it managed to delete the cookies. I recon this has to do with the fact that in order to overwrite a cookie, you need to be as specific as possible when adding the replacing cookies. Seeing as the former cookies was added without specifying domain nor path, this is the most specific.
The code that ended up working in this scenario, was therefor:
var myCookies = Request.Cookies.AllKeys;
foreach (var cookieName in myCookies)
{
var cookie = Request.Cookies[cookieName];
if (cookie == null) continue;
cookie.Value = "written " + DateTime.Now;
cookie.Expires = DateTime.Now.AddYears(-1);
Response.Cookies.Add(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.
I'm trying to get a subdomain to create a cookie for the entire domain instead of just its subdomian using the property cookie.domain, so the two subdomains can share the cookie info. When I deploy to IIS I get 2 cookies created, one for the domain and another for the subdomain. Why is that? When I update the cookie the only one that gets updated is the subdomain one, rendering the domain cookie kind of useless.
I tried to trace this through my code, but running visual studio in debug mode doesn't actually set any cookie at all, unless I don't set the cookie.domain property. Leaving domain.cookie out I get a cookie set to localhost, but only that one cookie. Any thoughts?
Okay, so I finally answered my own quesion(s). I'll tackle the second one first, about running the site in debug mode:
Visual studio debugs to the site http://localhost:[someport]. So if the code is set to create a cookie using cookie.domain for mydomain.com, the cookie isn't set because the browser knows you're at localhost instead of the domain specified. To remedy this I put an entry in my hosts file so that mydomain.com is pointed to 127.0.0.1. Then I fired up the site in debug mode. When the site came up as localhost I changed the URL in the browswer to http://subdomain.domain.com:[someport] and refreshed. Now the cookie can be set.
Doing this helped me trace through my code to find the issue of two cookies being created by my subdomain website. What I found is that the mydomain.com cookie was being created okay (CreateCookie method below) because of cookie.domain. However, when I was trying to update the expiration on the cookie (UpdateCookie below) it reverted back to thinking it should be using the subdomain cookie and went ahead and created it when it didn't find one. All I had to do was set cookie.domain again before setting the cookie and updating the expiration. Now I only have one cookie.
public void CreateCookie()
{
HttpCookie cookie = new HttpCookie(mConfig.webCookie);
TimeSpan span = new TimeSpan(0, 0, 30, 0);
DateTime time = DateTime.Now; ;
cookie["Username"] = mEncrypt.Encrypt(mUser.Username);
cookie.Domain = "mydomian.com";
cookie.Expires = time + span;
HttpContext.Current.Response.Cookies.Add(cookie);
}
public void UpdateCookie()
{
TimeSpan span = new TimeSpan(0, 0, 30, 0);
DateTime time = DateTime.Now;
HttpCookie cookie = HttpContext.Current.Request.Cookies[mConfig.webCookie];
// without specifying the domain the cookie will be set with the subdomain
cookie.Domain = "mydomain.com";
HttpContext.Current.Response.Cookies.Set(cookie);
HttpContext.Current.Response.Cookies[mConfig.webCookie].Expires = time + span;
}
You can set this cookie name for the full domain and subdomain on web.config on httpCookies
<httpCookies domain="domain.com" httpOnlyCookies="false" requireSSL="false" />
set domain.com and NOT www.domain.com to archive what you say, to have the same cookie on domain and sub domain. Similar there is a parameter on authentication that you set this cookie settings, depend for what cookie you talking about.
In your question "why is that?" the answer is that if you not set this parameters for the cookies then the cookies actually use the current host name, so they are different if the first name of the sub-domain change.
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