开发者

PDFHandler.ash error when there is no file

I am having an issue with my ASHX handler that is generating PDF.

When the user hits a "View PDF" button, it will look in the database for the PDF file and display it, but if there isn't a PDF file there it should display a blank page saying "no PDF available", but instead I get a "null reference" error on this line of code:

ms.WriteTo(context.Response.OutputStream)

Below is the code for the handler:

Public Sub ProcessRequest(ByVal context As HttpContext) Implements IHttpHandler.ProcessRequest
    'This c开发者_如何学运维lass 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

Can anyone tell me how to get rid of this error?


Simple If..Then should do the trick:

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


You probably want to move the following out of the if:

context.Response.End()

so it execute each time regardless.

However you say the following line executes when no PDF available:

ms.WriteTo(context.Response.OutputStream)

which would suggest something wrong with your if condition

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜