js代码var source = new EventSourceapi;sourceonmessage = functionevent consolelogeventdata;;sourceonerror = functionevent consolelogSSE请求出错;;sourceonclose = functionevent consolelogSSE请求完成;;后台是net4
在后台的webapi中,可以使用Response对象的Close()方法来关闭SSE连接。修改你的webapi代码如下:
public HttpResponseMessage Get() { var response = Request.CreateResponse(); response.Content = new PushStreamContent((stream, content, context) => { // 在stream中写入SSE数据 // ...
// 刷新stream
stream.Flush();
// 关闭SSE连接
response.Close();
});
response.Headers.Add("Content-Type", "text/event-stream");
return response;
}
当你在webapi中调用response.Close()方法时,SSE连接将被关闭,这将触发js代码中的source.onclose事件。
原文地址: https://www.cveoy.top/t/topic/8SX 著作权归作者所有。请勿转载和采集!