添加连接:keep-alive header 未在 ASP.net 中返回给客户端

Adding Connection: keep-alive header is not returned to client in ASP.net

精简版

我正在添加回复 header:

Connection: keep-alive

但它不在响应中。

长版

我正在尝试在 ASP.net 中添加 header to an HttpResponse:

public void ProcessRequest(HttpContext context)
{
    context.Response.CacheControl = "no-cache";
    context.Response.AppendHeader("Connection", "keep-alive");
    context.Response.AppendHeader("AreTheseWorking", "yes");
    context.Response.Flush();
}

并且当响应返回到客户端(例如 Chrome、Edge、Internet Explorer、Postman)时,Connection header 丢失:

HTTP/1.1 200 OK
Cache-Control: no-cache
Pragma: no-cache
Transfer-Encoding: chunked
Expires: -1
Server: Microsoft-IIS/10.0
AreTheseWorking: yes
X-AspNet-Version: 4.0.30319
X-Powered-By: ASP.NET
Date: Sat, 26 Feb 2022 16:29:17 GMT

我做错了什么?

奖金聊天

除了尝试AppendHeader

context.Response.AppendHeader("Connection", "keep-alive"); //preferred

我也尝试了 AddHeader (存在“为了与 ASP 的早期版本兼容”):

context.Response.AddHeader("Connection", "keep-alive"); // legacy

我也试过了Headers.Add:

context.Response.Headers.Add("Connection", "keep-alive"); //requires IIS 7 and integrated pipeline

我做错了什么?

奖金: hypothetical motivation for the question

默认情况下 ASP.net 中不允许 keep-alive

为了允许它,您需要将 an option 添加到您的 web.config:

web.config:

<configuration>
    <system.webServer>
        <httpProtocol allowKeepAlive="true" />
    </system.webServer>
</configuration>

这对 Server-Send Events:

尤为重要
public void ProcessRequest(HttpContext context)
{
   if (context.Request.AcceptTypes.Any("text/event-stream".Contains))
   {
      //Startup the HTTP Server Send Event - broadcasting values every 1 second.
      SendSSE(context);
      return;
   }
}
private void SendSSE(HttpContext context)
{
   //Don't worry about it.
   string sessionId = context.Session.SessionID; //

   //Setup the response the way SSE needs to be
   context.Response.ContentType = "text/event-stream";
   context.Response.CacheControl = "no-cache";
   context.Response.AppendHeader("Connection", "keep-alive");
   context.Response.Flush();

   while (context.Response.IsClientConnected)
   {
      System.Threading.Thread.Sleep(1000);
 
      String data = DateTime.Now.ToString();
      context.Response.Write("data: " + data + "\n\n");
      context.Response.Flush();
   }
}