添加连接:ASP.net中的保持活动标头不会返回到客户端



短版本

我正在添加响应标头:

Connection: keep-alive

但它不在呼吸系统里。

长版本

我正在尝试向ASP.net中的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标头丢失:

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

我还尝试了标头。添加:

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

我做错了什么?

奖金:问题的假设动机

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

为了允许它,您需要在web.config:中添加一个选项

web.config

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

这对于服务器发送事件特别重要:

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; //https://stackoverflow.com/a/1966562/12597
//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 + "nn");
context.Response.Flush();
}
}

最新更新