gpt4 book ai didi

c# - HttpContext 抛出 HttpException

转载 作者:IT王子 更新时间:2023-10-29 04:38:25 28 4
gpt4 key购买 nike

我已经编写了一个自定义的 http 处理程序。我通过编写一个实现 IHttphandler 的类来完成此操作。

在那个类中我有这样的代码,

context.Response.Clear();
context.Response.ClearHeaders();
context.Response.AddHeader("Content-Disposition", "attachment;filename=" + attachmentFileName);
context.Response.AddHeader("Content-Length", new FileInfo(downloadFile).Length.ToString());
context.Response.ContentType = GetMimeType(attachmentFileName);
context.Response.TransmitFile(downloadFile);
context.Response.Flush();
context.Response.Close();

偶尔我会收到这样的错误,

Exception HttpException The remote host closed the connection The error code is 0x800703E3

或者这个,

Exception HttpException The remote host closed the connection The error code is 0x80070040

在这两种情况下,堆栈跟踪都是这样的,

at System.Web.Hosting.IIS7WorkerRequest.RaiseCommunicationError(Int32 result, Boolean throwOnDisconnect)
at System.Web.Hosting.IIS7WorkerRequest.ExplicitFlush()
at System.Web.HttpResponse.Flush(Boolean finalFlush)
at System.Web.HttpResponse.Flush()

这发生在生产中,如果我回顾过去几天错误发生了 23 次,上面的代码总共被调用了 497 次。

我怀疑此故障与用户点击链接不止一次启动上述代码(这将给他们提供多个下载对话框)然后他们取消其中一些有关。话虽如此,如果是那样的话,我希望连接能够在两端优雅地关闭。

如何证明此错误的确切原因?我试过像这样启用 .NET 跟踪 Why don't trace listeners log custom handler traffic?但无法让它工作。

不过我发现我启用了 IIS 跟踪以记录失败的请求。故障再次发生,并且该日志中没有任何内容。

例如,我可以启用任何其他跟踪吗?

接下来我尝试的是这个,

if (context.Response.IsClientConnected)
{
context.Response.Flush();
context.Response.Close();
}
else
{
LogMessage("Client has disconnected before flush was called", Severity.Information);
}

但这没有任何区别。我猜原因是客户端在下载过程中断开连接,而不是在调用刷新之前断开连接。

最佳答案

取出 Flush()Close() 调用。你真的不需要它们。处理程序完成后,它将退出,ASP.NET 将处理关闭请求。

此外,Flush() 应该在您将内容流式传输到客户端时使用(以 block 的形式将部分添加到响应流)。您不需要将它与 TransmitFile() 一起使用。

关于c# - HttpContext 抛出 HttpException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5533068/

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