HttpListenerResponse添加不需要的Set-Cookie标头

时间:2016-10-19 11:48:16

标签: c# cookies httplistener

我尝试使用C#处理HttpListener类,它似乎发送了一个不需要的Set-Cookie标头,同时阻止了我的cookie被发送。

拥有HttpListenerContext context,请求正在以某种方式处理,然后响应部分就是这样:

    if (responseHeaders != null)
        foreach (string header in responseHeaders.Keys)
            context.Response.Headers.Add(header, responseHeaders[header]);
    for (int i = 0; i < responseCookies.Count; i++)
    {
        context.Response.Headers.Add("Set-Cookie", responseCookies[i].ToHeaderString());
    }
oWrite(response, responseEncoding);
oClose();

我的扩展方法ToHeaderString()

    public static string ToHeaderString(this Cookie c)
    {
        string s = c.Name + "=" + c.Value;
        if (c.Path != null && c.Path != string.Empty)
        {
            s += "; path=" + c.Path;
        }
        if (c.Domain != null && c.Domain != string.Empty)
        {
            s += "; domain=" + c.Domain;
        }
        if (c.Expires != null)
        {
            s += "; expires=" + c.Expires.ToString("ddd, d MMM yyyy HH:mm:ss", new CultureInfo("en-US")) + " GMT";
        }
        return s;
    }

responseHeaders的类型为Dictionary<string, string>responseCookies的类型为CookieCollection。他们都填充了要发送给客户端的标题和Cookie。

Cookie userCookie = new Cookie("username", _GET["__username"], "/");
userCookie.Expires = DateTime.Now.AddDays(10);
_CONNECTION.responseCookies.Add(userCookie);
Cookie userSession = new Cookie("session", ses, "/");
userSession.Expires = DateTime.Now.AddDays(10);
_CONNECTION.responseCookies.Add(userCockie);
_CONNECTION.responseCookies.Add(userSession);

不过,我所看到的反应是:

Date:Wed, 19 Oct 2016 11:33:21 GMT
Server:Microsoft-HTTPAPI/2.0
Set-Cookie:username=yotam180; Max-Age=863999; Path=/, session=XCDbRv0fqbUwWC9g9xXL; Max-Age=863999; Path=/
Transfer-Encoding:chunked

我在这里做错了什么?我没有正确使用HttpListenerResponse标题吗?

谢谢!

编辑我也尝试过使用context.Response.Cookies.Add(..),但也没有成功。这是正确的方法吗?或者有没有可以在这里使用的技巧?

1 个答案:

答案 0 :(得分:0)

好吧,我终于找到了我错误的地方。

在我给出的代码之前有一个赋值应该是初始化。基本上,分配CookieCoolection A = context.Response.Cookies而不是CookieCollection A = new CookieCollection,会将context.Response.Cookies的Cookie输入到集合中两次,我猜这是导致问题的原因。