簡潔版本
我正在添加回應標頭:
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
我也試過Headers.Add:
context.Response.Headers.Add("Connection", "keep-alive"); //requires IIS 7 and integrated pipeline
我在做什么錯?
獎勵: 問題的假設動機
uj5u.com熱心網友回復:
默認情況下keep-alive,在 ASP.net 中是不允許的。
為了允許它,您需要添加一個選項到您的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 "\n\n");
context.Response.Flush();
}
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/435130.html
上一篇:使用C#ASP.NET使用主GridView和子GridView的網站
下一篇:防止表單進入空格并插入資料庫
