gpt4 book ai didi

c# - 客户端已断开连接,因为基础请求已完成。不再有可用的 HttpContext

转载 作者:太空狗 更新时间:2023-10-29 23:28:11 25 4
gpt4 key购买 nike

我们间歇性地得到一个客户端断开连接,因为底层请求已经完成。我们的 WebApi 端点中不再有可用的 HttpContext 异常。

有谁知道导致此错误的原因,或者如何以一致的方式重现此错误?目前,每 100,000 个请求中就有 150 个会发生这种情况。

异常是在这部分代码中被XmlDeserialize()抛出的:

[HttpPost]
public async Task<IHttpActionResult> Process()
{
using (var requestStream = await Request.Content.ReadAsStreamAsync())
{
XmlSerializer serializer = new XmlSerializer(typeof(MyEntity));

// !! The below line throws the exception
MyEntity entity = serializer.Deserialize(requestStream) as MyEntity;
}
...
}

这是完整的异常信息:

  "ExceptionType": "HttpException",
"Message": "The client is disconnected because the underlying request has been completed. There is no longer an HttpContext available.",
"StackTrace": [
"HttpBufferlessInputStream.Read;0",
"SeekableBufferedRequestStream.Read;0",
"XmlTextReaderImpl.ReadData;0",
...

编辑:我在 .NET 的源代码中找到了这个。 System.Web.txt :

HttpBufferlessInputStream_ClientDisconnected=The client is disconnected because the underlying request has been completed. There is no longer an HttpContext available.

https://referencesource.microsoft.com/#system.web/HttpBufferlessInputStream.cs,332ecbede7a1f12a :

// We are done if the count == 0 or there is no more content
while (count > 0 && _remainingBytes != 0) {
// Do the actual read
bytesRead = wr.ReadEntityBody(buffer, offset, count);
if (bytesRead <= 0) {
if (!_context.Response.IsClientConnected) {
if (_persistEntityBody) {
SetRawContentOnce();
}
throw new HttpException(SR.GetString(SR.HttpBufferlessInputStream_ClientDisconnected));

因此异常是由 HttpBufferlessInputStream.Read() 抛出的,在 wr.ReadEntityBody(buffer, offset, count) 返回 0 或负数之后,并且 _context.Response.IsClientConnected 是错误的。

这意味着客户端在 XmlDeserialize() 仍在运行时断开连接。但是从我对 netcat 的有限实验来看,.NET 会等到整个 XML 请求都已上传,然后才会调用 Controller 方法。因此,我们仍在反序列化时不会上传请求。

最佳答案

就像解释的那样here您应该避免捕获同步上下文并使用 .ConfigureAwait(false);

[HttpPost]
public async Task<IHttpActionResult> Process()
{
using (var requestStream = await Request.Content.ReadAsStreamAsync().ConfigureAwait(false))
{
XmlSerializer serializer = new XmlSerializer(typeof(MyEntity));
MyEntity entity = serializer.Deserialize(requestStream) as MyEntity;
}
...
}

注意到 Thowk , SynchronizationContext has been removed from ASP.NET Core .

关于c# - 客户端已断开连接,因为基础请求已完成。不再有可用的 HttpContext,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56833004/

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