I am working with cookies and I happened to create it using JavaScript ,but when I try to expire that cookie after my process is completed,using C# code behind file ,there I am unable to find the specified Cookie??
What could be the reason for this?? I think cookies created in JavaScript are not accessible/Visible using C# ...? Is that true??
Here is my code for creating cookie in JS
var expiryDate = new Date();
expiryDate.setTime(expiryDate.setDate(expiryDate.getDate() + 1)); // 365 days
document.cookie = "ReferedCookie=" + "clientId=" + UserGuid + "&productId=" + productId + "&Token=" + token + ";" + "expires=" + expiryDate.toGMTString() + ";";
and here is my C# code for finding and expiring cookie
public void DeleteCookie(string Name)
{
if (System.Web.HttpContext.Current.Request.Cookies["ReferedCookie"] != null)
{
HttpCookie myCookie = new HttpCookie(Name);
myCookie.Expires = DateTime.Now.AddDays(-5d);
System.Web.HttpContext.Current.Response.Cookies.Add(myCookie);
}
}
Thanks in advance.
The problem is likely with the Path property of the cookie.
When setting a cookie using Javascript, the default path of the cookie will be based on the location of the page that sets the cookie.
In order to expire that cookie, you must specify the same path. So if you have a page:
http://test.foo.com/somepath/default.asxp
and you use the javascript code you had in your question to set a cookie on this page, the default path of the cookie will be:
/somepath/
This means the browser will send this cookie to all pages that are under that path. It will not be sent to pages outside that path.
To expire this cookie from the server, you need to specify the path of the cookie:
HttpCookie myCookie = new HttpCookie(Name);
myCookie.Expires = DateTime.Now.AddDays(-5d);
myCookie.Path = "/somepath/";
System.Web.HttpContext.Current.Response.Cookies.Add(myCookie);
Alternatively you must specify the path when originally setting the cookie to (for instance) /:
document.cookie = "ReferedCookie=" + "clientId=" + UserGuid + "&productId=" + productId + "&Token=" + token + ";" + "expires=" + expiryDate.toGMTString() + ";path=/";
and then expire it on the same path.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With