Question

I add acces token to users cookies, first time when I check if it is still there, it is. But next time I look for it, it isn't there. Does it get deleted when I get it from cookies? Or what I got wrong?

This is how I add cookie:

        HttpCookie cookie = new HttpCookie(key);
        cookie.Expires = DateTime.Now.AddMinutes(10);       
        HttpContext.Current.Request.Cookies.Add(cookie);
Was it helpful?

Solution

You are doing just a little mistake, to add cookies use Response rather than Request

Corrected code:

 HttpCookie cookie = new HttpCookie(key);
 cookie.Value = value;
 cookie.Expires = DateTime.Now.AddMinutes(10);
 HttpContext.Current.Response.Cookies.Add(cookie);

OTHER TIPS

For security reasons, you can read only cookies that are set by pages that are part of the same domain. If the cookie's Path property has been set, that cookie is available only to pages and subfolders within that path of the domain.

http://msdn.microsoft.com/en-us/library/bd70eh18%28v=vs.100%29.aspx

You might check that you're not trying to read the cookie from a different page than it was set.

Also see this page: http://msdn.microsoft.com/en-us/library/system.web.httprequest.cookies%28v=vs.110%29.aspx

ASP.NET includes two intrinsic cookie collections. The collection accessed through the Cookies collection of HttpRequest contains cookies transmitted by the client to the server in the Cookie header. The collection accessed through the Cookies collection of HttpResponse contains new cookies created on the server and transmitted to the client in the Set-Cookie header.

After you add a cookie by using the HttpResponse.Cookies collection, the cookie is immediately available in the HttpRequest.Cookies collection, even if the response has not been sent to the client.

You're setting the Cookie in the Request collection and then trying to read it back out. Perhaps you should try reading it from the Response.Cookies collection instead?

I.e. change

HttpCookie cookie = HttpContext.Current.Request.Cookies[key];

to

HttpCookie cookie = HttpContext.Current.Response.Cookies[key];
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top