我的ASHX处理程序出现了问题,即生成PDF。
当用户点击“查看PDF”按钮时,它将在数据库中查找PDF文件并显示它,但如果没有PDF文件,则应显示一个空白页面,上面写着“没有PDF可用” ,但我在这行代码中得到一个“空引用”错误:
ms.WriteTo(context.Response.OutputStream)
以下是处理程序的代码:
Public Sub ProcessRequest(ByVal context As HttpContext) Implements IHttpHandler.ProcessRequest
'This class takes the uniqueidentifier of an image stored in the SQL DB and sends it to the output stream
'This saves storing copies of image files on the web server as well as in the DB
context.Response.Clear()
If context.Request.QueryString("fileSurveyID") IsNot Nothing Then
Dim filesID As String = context.Request.QueryString("fileSurveyID")
Dim fileName = String.Empty
Dim ms As MemoryStream = GetPDFFile(filesID)
context.Response.ContentType = "application/pdf"
context.Response.AddHeader("Content-Disposition", "attachment;filename=" & fileName)
context.Response.Buffer = True
ms.WriteTo(context.Response.OutputStream)
context.Response.End()
Else
context.Response.Write("<p>No pdf file</p>")
End If
End Sub
有谁能告诉我如何摆脱这个错误?
答案 0 :(得分:0)
您可能希望将以下内容移出if
:
context.Response.End()
所以无论如何都会执行。
但是,如果没有可用的PDF,则表示执行以下行:
ms.WriteTo(context.Response.OutputStream)
这会导致您的if
条件
答案 1 :(得分:0)
简单If..Then
应该可以解决问题:
Dim ms As MemoryStream = GetPDFFile(filesID)
If ms IsNot Nothing Then
context.Response.ContentType = "application/pdf"
context.Response.AddHeader("Content-Disposition", "attachment;filename=" & fileName)
context.Response.Buffer = True
ms.WriteTo(context.Response.OutputStream)
context.Response.End()
End If