【发布时间】:2017-09-26 23:34:48
【问题描述】:
我有一个我编写的方法,它调用 ReportServer 并返回报告的 pdf 的字节数组。这行得通。我知道是因为我使用相同的方法将 pdf 写入文件并将其保存在本地。在这里,我想将文件写入内存流并作为下载提供。
Try
Dim ms As MemoryStream = New MemoryStream(report, 0, report.Length)
ms.Position = 0
Response.Clear()
Response.Expires = 0
Response.Buffer = True
Response.AddHeader("Content-disposition", "attachment;filename=UserReport.pdf")
Response.ContentType = "application/pdf"
'ms.WriteTo(Response.OutputStream)
Response.BinaryWrite(ms.ToArray())
Response.End()
HttpContext.Current.ApplicationInstance.CompleteRequest()
'Response.Flush()
Catch ex As Exception
lblERRORMSG.Visible = True
lblERRORMSG.Text = "Darn!" & ex.Message
Return
End Try
End Sub`
这段代码可以编译、运行,我什至可以设置被命中的断点。但是当按钮被点击时,什么也没有发生。
【问题讨论】:
-
HttpContext.Current.ApplicationInstance.CompleteRequest()永远不会受到打击。Response.End()按设计抛出ThreadAbortException。 -
我已经看到 Response.End() 抛出异常,但消息是一个空字符串,所以我想保留该代码以捕获任何其他异常。
-
您应该将 Response.End 移到 try/catch 之外。并抛弃 CompleteRequest。
-
仍然没有给我下载。我还摆脱了 Catch 中的返回...我认为这会导致 Response.End() 被跳过。
-
使用浏览器的调试工具检查网络流量。当您尝试下载时会发生什么?