Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# HttpListener Cookies expiring after session even though expiration time set

I have an HttpListener class for handling logins to a page, and can successfully set the cookie, but the cookie is expiring at the end of the session (using cookie extension in Chrome, shows cookie is a session cookie). Here is the code snippet:

CookieCollection ccol = new CookieCollection();    
Cookie loginCookie = new Cookie();

loginCookie.Name = "login";
loginCookie.Value = "loggedin";
loginCookie.Expires = DateTime.Now.AddMinutes(60);
ccol.Add(loginCookie);
context.Response.Cookies = ccol;

As long as I am in the same session I can access the cookie without issue.

like image 769
Mike J Avatar asked Jan 26 '11 22:01

Mike J


2 Answers

Normally, the cookie collection (Cookies) property is read only (at least when using the ASP.NET Response.Cookies property).

It's been a while since I used the HttpListener, so do you know if the Cookies collection is null prior to assigning your own cookie collection? If not, can you try simply adding a cookie rather than a cookie collection?

Edit:

I built a test webserver using HttpListener and this is what I found. When you set a cookie the http header looks like this:

Set-Cookie: username=shiv

whereas it should really be something like:

Set-Cookie: username=shiv; expires=Thu, 27-Jan-2011 00:45:41 GMT; path=/

So for the moment it looks like a bug? I'll dig deeper and let you know...

Edit 2:

Ok, the Expiration time of cookies needs to be set as GMT time. ASP.NET takes care of this for you, but in this case you'll have to use the proper format yourself.

Manually setting the Http Header works as expected:

context.Response.Headers.Add("Set-Cookie", 
"username=shiv; expires=Thu, 27-Jan-2011 00:45:41 GMT; path=/");

where context is HttpListenerContext.

This seems to be the only way to set a (non session) cookie using the HttpListener. You can use this DateTime format string to format the date correctly if you go down the route I suggested:

var cookieDate = DateTime.UtcNow.AddMinutes(60d).ToString("dddd, dd-MM-yyyy hh:mm:ss GMT");
like image 77
Shiv Kumar Avatar answered Sep 30 '22 01:09

Shiv Kumar


Solved it by doing the following:

string cookieDate = DateTime.UtcNow.AddMinutes(60).ToString("ddd, dd-MMM-yyyy H:mm:ss");

context.Response.Headers.Add("Set-Cookie", "cookieName=cookieValue;Path=/;Expires=" + cookieDate + " GMT");
like image 25
Mike J Avatar answered Sep 30 '22 01:09

Mike J