我在使用 Internet Explorer 11 时遇到了关于持久性 cookie 的问题,也就是说,我可以设置 cookie,但无法使它们持久化。我尝试过“Internet 选项”->“高级”->“重置”,但没有帮助。
以下是我的测试代码:
现在,当访问
为什么会这样?我做错了什么吗?肯定有一种方法可以在C#服务器上设置IE中的持久性cookie吧?
以下是我的测试代码:
class Program {
public static void Main(string[] args) {
HttpListener listener = new HttpListener();
listener.Prefixes.Add("http://+:7777/");
listener.Start();
ThreadPool.QueueUserWorkItem((o) = > {
while (listener.IsListening) {
ThreadPool.QueueUserWorkItem((c) = > {
HandleRequest(c as HttpListenerContext);
}, listener.GetContext());
}
});
Console.Write("Press any key to quit . . . ");
Console.ReadKey(true);
listener.Stop();
listener.Close();
}
static void HandleRequest(HttpListenerContext ctx) {
var cookie = ctx.Request.Cookies["TestCookie"];
if (cookie == null) {
Console.WriteLine("Setting cookie...");
var expiryDate = DateTime.UtcNow.AddDays(360);
ctx.Response.Headers["Set-Cookie"] = "TestCookie=some_value; Path=/; Expires=" + expiryDate.ToString("ddd, dd-MMM-yyyy H:mm:ss") + " GMT; HttpOnly";
} else {
Console.WriteLine("Cookie: " + cookie);
}
ReturnString(ctx, "OK");
}
protected static void ReturnString(HttpListenerContext ctx, String s) {
try {
byte[] buf = Encoding.UTF8.GetBytes(s);
ctx.Response.ContentLength64 = buf.Length;
ctx.Response.OutputStream.Write(buf, 0, buf.Length);
} catch (Exception e) {
} // suppress any exceptions
finally {
// always close the stream
ctx.Response.OutputStream.Close();
}
}
}
现在,当访问
127.0.0.1:7777
时,我首先会得到“设置cookie”,然后在所有后续请求中都会得到“Cookie:TestCookie = some_value”。在Chrome中,cookie是持久的(我可以关闭浏览器,重新启动它,仍然可以得到“Cookie:TestCookie = some_value”),但是在Internet Explorer中无法实现。也就是说,在使用IE时,每次重新启动浏览器时,我都会在第一个请求上收到“设置cookie”。因此,该cookie显然不再存在。为什么会这样?我做错了什么吗?肯定有一种方法可以在C#服务器上设置IE中的持久性cookie吧?