2011-12-30 137 views
2

ASP.Net MVC 3FileStreamResult錯誤處理

我有一個Action,它在導入PDF文檔並返回一個水印後返回一個FileStreamResult。由於可能有文件未找到錯誤,因此如何返回視圖而不是文件流?

使用Philip Hutchison的jQuery PDFObject(http://pdfobject.com)來調用動作並將其呈現在DIV中使我無法在服務器端重定向。

重申:它是頁面上的一個jQuery鏈接,它使用PDF文件流的結果填充DIV。我能想到的唯一'黑客'就是發送一個Error.pdf文件。

您的想法?

回答

0

我最終創建了一個錯誤的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(); 
    }