in my app. there\'s a log in mechanism which save a cookie with the info of the user who just logged in
private void CreateCookie(LoginEventArgs args)
o'k , the problem was unthinkable
special thanks to Peter Bromberg
http://www.eggheadcafe.com/tutorials/aspnet/198ce250-59da-4388-89e5-fce33d725aa7/aspnet-cookies-faq.aspx
in the section of the Article " The Disappearing Cookie "
the author states that if you have a watch on Response.Cookies["cookie_name"] the browser creates a new empty cookie that overrides your cookie .
i used such a watch which made my cookie loose it's values ,and when i took it off the cookie kept its values.
the moral is DON't WATCH Response.Cookies[" "] also i read in some other post that if you check
if( Response.Cookies["cookie_name"] != null )
for example it also gets overridden.
Use the following approach to get a value from cookies:
public string GetValueFromCookies(HttpCookieCollection cookies)
{
if (cookies == null)
{
throw new ArgumentNullException(nameof(cookies));
}
// check the existence of key in the list first
if (Array.IndexOf(cookies.AllKeys, key) < 0)
{
return null;
}
// because the following line adds a cookie with empty value if it's not there
return cookies[key].Value;
}
try the following:
To reiterate and build upon what has already been stated (yes, I know this is a 4 year old question) I have found it best to build a utility to handle this - mostly because I want to check that specific cookie often.
This will not touch the Response but only read from the Request.
public static HttpCookie GetCookie(string cookieName)
{
HttpCookie rqstCookie = HttpContext.Current.Request.Cookies.Get(cookieName);
/*** NOTE: it will not be on the Response!
* this will trigger the error noted in the original question and
* create a new, empty cookie which overrides it
*
HttpCookie respCookie = HttpContext.Current.Response.Cookies.Get(cookieName);
*
*/
if (rqstCookie != null && !String.IsNullOrEmpty(rqstCookie.Value))
{
// is found on the Request
return rqstCookie;
}
else
{
return null;
}
}
Always read from the Request and write to the Response.
Thanks eran! this post was exactly what I needed