Gabe
Gabe

Reputation: 50503

Convert asp.net webforms logic to asp.net MVC

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?

Here's my asp.net webforms code:

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

Upvotes: 2

Views: 240

Answers (1)

Dave Swersky
Dave Swersky

Reputation: 34810

Here is a blog post on exactly that: http://biasecurities.com/blog/2008/binaryresult-for-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.

Upvotes: 2

Related Questions