【问题标题】:FileStreamResult Error HandlingFileStreamResult 错误处理
【发布时间】:2012-01-30 19:13:13
【问题描述】:

ASP.Net MVC 3

我有一个 Action,它在导入 PDF 文档并在其上加盖水印后返回 FileStreamResult。由于可能出现未找到文件的错误,如何返回视图而不是文件流?

为了使事情复杂化,我使用 Philip Hutchison 的 jQuery PDFObject (http://pdfobject.com) 来调用操作并将其呈现在 DIV 中,因此我无法在服务器端重定向。

重申一下:它是页面上的一个 jQuery 链接,它使用 PDF 文件流的结果填充 DIV。我能想到的唯一“hack”就是发送一个 Error.pdf 文件。

你的想法?

【问题讨论】:

    标签: asp.net-mvc error-handling filestreamresult


    【解决方案1】:

    我最终创建了一个错误的 PDF 内存流。

    MemoryStream ms = new MemoryStream();
    try
        {
            PdfReader reader = new PdfReader(readerURL);
            StampWatermark(WO, ms, reader);
        }
    
    catch (Exception ex)
        {
            RenderErrorPDF(WO, ms, ex);
        }
    
    byte[] byteinfo = ms.ToArray();
    ms.Write(byteinfo, 0, byteinfo.Length);
    ms.Position = 0;
    ms.Seek(0, SeekOrigin.Begin);
    return new FileStreamResult(ms, "application/pdf");
    

    RenderErrorPDF 方法

    private static void RenderErrorPDF(WorkOrder WO, MemoryStream ms, Exception ex)
        {
            BaseFont bfTimes = BaseFont.CreateFont(BaseFont.HELVETICA_BOLD, BaseFont.CP1250, false);
            var doc = new Document(new Rectangle(792f, 540f));
            var wr = PdfWriter.GetInstance(doc, ms);
            doc.Open();
            doc.Add(new Paragraph("There was an error rendering the file that you requested...", new Font(bfTimes, 24f)));
            doc.Add(new Paragraph(string.Format("\r\rFile: {0}", WO.DRAWING_FILE)));
    
            doc.Add(new Paragraph(string.Format("\r\rError: {0}", ex.Message)));
            wr.CloseStream = false;
            doc.Close();
        }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2022-12-05
      • 2016-08-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2010-12-31
      相关资源
      最近更新 更多