2010-05-17 128 views
2

我在舊的asp.net webforms應用程序中使用此代碼以獲取MemoryStream並將其作爲顯示PDF的Response作爲響應傳遞給它。我現在正在使用一個asp.net MVC應用程序,並希望這樣做同樣的事情,但我應該如何去使用MVC將MemoryStream顯示爲PDF?將asp.net webforms邏輯轉換爲asp.net MVC

這裏是我的asp.net web表單代碼:

private void ShowPDF(MemoryStream ms) 
    { 
     try 
     { 
      //get byte array of pdf in memory 
      byte[] fileArray = ms.ToArray(); 
      //send file to the user 
      Page.Response.Cache.SetCacheability(HttpCacheability.NoCache); 
      Page.Response.Buffer = true; 
      Response.Clear(); 
      Response.ClearContent(); 
      Response.ClearHeaders(); 
      Response.Charset = string.Empty; 
      Response.ContentType = "application/pdf"; 
      Response.AddHeader("content-length", fileArray.Length.ToString()); 
      Response.AddHeader("Content-Disposition", "attachment;filename=TID.pdf;"); 
      Response.BinaryWrite(fileArray); 
      Response.Flush(); 
      Response.Close(); 
     } 
     catch 
     { 
      // and boom goes the dynamite... 
     } 
    } 

回答

2

這裏是正是博客文章:http://biasecurities.com/blog/2008/binaryresult-for-asp-net-mvc/

UPDATE:該帖子的最後註釋中提到Response.TransmitFile,你可能想調整代碼以使用如果您的PDF文件很大並且您將有大量的併發下載。

+0

謝謝,我使用'Response.TransmitFile'實現了它,一切正常。 +1 – Gabe 2010-05-17 18:16:42