通过HttpListenerResponse

时间:2018-07-27 19:28:42

标签: c# .net cookies httplistener

我正在尝试通过响应将多个cookie添加到客户端Web浏览器。

首先,我使用System.Net.HttpListenerResponse.SetCookie方法将多个cookie对象添加到标头中,然后发送回响应。根据文档,此方法“在与此响应一起发送的cookie集合中添加或更新cookie。”

当我在浏览器开发人员工具中查看cookie时,我看到仅添加了一个cookie。我的第二个Cookie的名称和值似乎已附加到我的第一个Cookie的值上。

Chrome Developper Tools - Cookies Image

我编写了一个简单的控制台应用程序,以演示您需要做的就是将“ 127.0.0.1 website.test.com”添加到主机文件中,URL将会解析。

using System.Net;
using System.IO;

namespace ConsoleApp1
{
    class Program
    {
        static void Main(string[] args)
        {
            using (HttpListener listener = new HttpListener())
            {
                listener.Prefixes.Add(@"http://website.test.com/cookies/");
                listener.Start();
                HttpListenerContext context = listener.GetContext(); //Waits for an incoming request
                HttpListenerRequest request = context.Request;
                HttpListenerResponse response = context.Response;
                response.SetCookie(new Cookie("name1", "value1"));
                response.SetCookie(new Cookie("name2", "value2"));
                response.StatusCode = (int)HttpStatusCode.OK;
                Stream responseStream = response.OutputStream;
                StreamWriter writer = new StreamWriter(responseStream);
                writer.Write("");
                response.Close();
            }
        }
    }
}

我还尝试在值的末尾添加分号。这将我的第二个cookie附加到我的第一个cookie值之后,但客户端中仍然只有一个cookie,从而解决了该问题。

1 个答案:

答案 0 :(得分:1)

HttpListenerResponse将所有cookie折叠为一个Set-Cookie标头:

HTTP/1.1 200 OK
Server: Microsoft-HTTPAPI/2.0
Set-Cookie: name1=value1, name2=value2

折叠式cookie被现代浏览器忽略。详细信息在这里:Is it possible to set more than one cookie with a single Set-Cookie?

每个cookie都应在单独的标题中:

HTTP/1.1 200 OK
Server: Microsoft-HTTPAPI/2.0
Set-Cookie: name1=value1
Set-Cookie: name2=value2

将cookie作为标头添加到HttpListenerResponse以获得所需的响应:

static void Main(string[] args)
{
    using (HttpListener listener = new HttpListener())
    {
        listener.Prefixes.Add(@"http://website.test.com/cookies/");
        listener.Start();
        HttpListenerContext context = listener.GetContext();
        HttpListenerResponse response = context.Response;
        response.StatusCode = (int)HttpStatusCode.OK;
        response.AddHeader("Set-Cookie", "name1=value1");
        response.AppendHeader("Set-Cookie", "name2=value2");
        response.Close();
    }
}