将asp.net webforms逻辑转换为asp.net MVC

时间:2020-12-31 03:21:54

I had this code in an old asp.net webforms app to take a MemoryStream and pass it as the Response showing a PDF as the response. I am now working with an asp.net MVC application and looking to do this this same thing, but how should I go about showing the MemoryStream as PDF using MVC?

我在一个旧的asp.net webforms应用程序中使用了这段代码来获取一个MemoryStream,并将其作为响应传递,显示为PDF作为响应。我现在正在使用一个asp.net MVC应用程序,并希望做同样的事情,但是我应该如何使用MVC将MemoryStream显示为PDF呢?

Here's my asp.net webforms code:

这是我的asp.net webforms代码:

    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...
        }
    }

1 个解决方案

#1


2  

Here is a blog post on exactly that: http://biasecurities.com/blog/2008/binaryresult-for-asp-net-mvc/

下面是一篇博客文章:http://biasecurities.com/blog/2008/binaryresultfor -asp-net-mvc/

UPDATE: The last comment on that post mentions Response.TransmitFile, you may want to adapt the code to use that if your PDFs are big and you will have a lot of concurrent downloads.

更新:这篇文章的最后一个评论提到了回应。如果你的pdf文件很大,并且你有很多并发下载,你可能想调整代码来使用它。

#1


2  

Here is a blog post on exactly that: http://biasecurities.com/blog/2008/binaryresult-for-asp-net-mvc/

下面是一篇博客文章:http://biasecurities.com/blog/2008/binaryresultfor -asp-net-mvc/

UPDATE: The last comment on that post mentions Response.TransmitFile, you may want to adapt the code to use that if your PDFs are big and you will have a lot of concurrent downloads.

更新:这篇文章的最后一个评论提到了回应。如果你的pdf文件很大,并且你有很多并发下载,你可能想调整代码来使用它。