cat_in_hat
cat_in_hat

Reputation: 685

HttpListenerResponse adding a 2nd cookie makes all cookies disappear

I have the following code:

    void WriteConnectionId(HttpListenerContext context, string id)
    {
        var cookie = context.Response.Cookies[CookieConnectionId];
        if (cookie == null)
        {
            cookie = new Cookie(CookieConnectionId, id)
            {
                HttpOnly = true,
                Secure = true,
                Path = "/"
            };
            context.Response.Cookies.Add(cookie);
        }
        else
        {
            cookie.Value = id;
        }
        //context.Response.SetCookie(new Cookie("lalala", "lololo"));
    }

This code stores correctly the cookie for "connection Id" in the client. In Chrome's console I can see the cookie in the list of cookies.

However, if I uncomment the last line that adds an extra cookie, then neither the session cookie or the dummy cookie make it to the client. They do not appear in Chrome's console.

Edit: removing the "/" path on the first cookie makes the first cookie appear, though with both values from the 1st and 2nd cookie concatenated with a comma.

Upvotes: 2

Views: 177

Answers (2)

cat_in_hat
cat_in_hat

Reputation: 685

I ended up fixing this issue by creating the following function:

    void FlushCookie(HttpListenerContext context, Cookie cookie)
    {
        var builder = new StringBuilder();
        builder.Append(cookie.Name);
        builder.Append("=");
        builder.Append(HttpUtility.HtmlAttributeEncode(cookie.Value));
        builder.Append(";");
        context.Response.Headers.Add(HttpResponseHeader.SetCookie, builder.ToString());
    }

This can be modified further to add cookie expiration, path, etc.

Upvotes: 1

spodger
spodger

Reputation: 1679

Try

context.Response.AppendCookie(new Cookie("lalala", "lololo"));

Upvotes: 1

Related Questions