c# - HttpContext 抛出 HttpException

标签 c# asp.net .net iis-7 httpexception

我已经编写了一个自定义的 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/

相关文章:

c# - 验证方法错误

c# - Microsoft BotFramework v4 任务计划和状态

c# - Nancy 模型是否根据文档绑定(bind)到字段?

ASP.NET/IIS 安全(Windows 身份验证)

c# - 同步等待一个异步操作,Wait()为什么会在这里卡住程序

c# - Socket.EndReceive(...) 没有正确返回

c# - 当返回类型是泛型接口(interface)时,如何将对象转换为泛型返回类型?

c# - 字符串的 System.FormatException

asp.net - 用于 ASP.NET 的 web api - 如何构建对象流

c# - 对象是如何存储在内存中的?