gpt4 book ai didi

asp.net-web-api - 在 Web API 中检测客户端与 PushStreamContent 的断开连接

转载 作者:行者123 更新时间:2023-12-03 23:25:02 26 4
gpt4 key购买 nike

虽然 HTTP 是一个无状态协议(protocol),但有一个 PushStreamContent 类可以促进服务器发送事件,如您所见 here . Web API 实现可以存储客户端流并定期发送推送更新。但是,检测客户端何时断开连接有点问题。
this discussion , Henrik Nielsen 指出:

Detecting that the TCP connection has been reset is something that the Host (ASP, WCF, etc.) monitors but in .NET 4 neither ASP nor WCF tells us (the Web API layer) about it. This means that the only reliable manner to detect a broken connection is to actually write data to it. This is why we have the try/catch around the write operation in the sample. That is, responses will get cleaned up when they fail and not before.

In .NET 4.5 there is a mechanism for detecting client disconnect but I haven't tried it out.


快进两年半到今天。有谁知道这种机制是什么,以及它是否有效?

最佳答案

此链接上发布了一个有趣的响应:link to the article

这是答案的一部分

在 .NET 4.5 中有一种检测客户端断开连接的机制,但我还没有尝试过。

这个(简化的)代码对我有用:

public HttpResponseMessage Get(HttpRequestMessage request)

{

// Register for client disconnect notifications

object clientId = ...; // this is the object passed to the callback

System.Web.HttpContext.Current.Response.ClientDisconnectedToken.Register(

delegate (object obj)

{

// Client has cleanly disconnected

// obj is the clientId passed in to the register

// handle client disconnection

//...



}


, 客户标识);

//示例中的正常代码继续

response.Content = new PushStreamContent(...);


}

ClientDisconnect 回调被回调,例如您干净地关闭客户端浏览器页面,但如果您拔出网线,它不会收到通知。所以对于这种不干净的断线,我们还是需要一些其他的方法来检测,比如在定时器回调的时候监控失败。

关于asp.net-web-api - 在 Web API 中检测客户端与 PushStreamContent 的断开连接,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27991602/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com