【问题标题】:PDFHandler.ash error when there is no file没有文件时出现PDFHandler.ash错误
【发布时间】:2011-09-13 12:23:42
【问题描述】:

我的 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

谁能告诉我如何摆脱这个错误?

【问题讨论】:

    标签: asp.net vb.net ashx


    【解决方案1】:

    简单的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
    

    【讨论】:

      【解决方案2】:

      您可能希望将以下内容移出if

      context.Response.End()
      

      所以它每次都会执行。

      但是你说当没有可用的 PDF 时执行以下行:

      ms.WriteTo(context.Response.OutputStream)
      

      这表明您的 if 条件有问题

      【讨论】:

      • 您好,感谢您的回复,这是我尝试查看时收到的错误。 System.NullReferenceException:对象引用未设置为对象的实例。
      猜你喜欢
      • 2011-06-26
      • 1970-01-01
      • 1970-01-01
      • 2013-12-07
      • 1970-01-01
      • 1970-01-01
      • 2018-05-03
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多