【问题标题】:Add multiple cookies to clients web browser via HttpListenerResponse通过 HttpListenerResponse 向客户端 Web 浏览器添加多个 cookie
【发布时间】:2018-07-27 19:28:42
【问题描述】:

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

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

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

我编写了一个简单的控制台应用程序来演示该行为,您只需将“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 的问题。

【问题讨论】:

    标签: c# .net cookies httplistener


    【解决方案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();
        }
    }
    

    【讨论】:

    • 感谢您的详细解释和解决方案。这解决了问题。
    猜你喜欢
    • 2010-11-14
    • 2015-07-22
    • 2017-08-25
    • 2015-07-18
    • 1970-01-01
    • 1970-01-01
    • 2016-06-15
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多