The remote host closed the connection - asp.net MVC3

0

and I keep getting this error message when my website builds a PDF and opens the dialog to allow the user to Save it or Open it.

This is the full error in Elmah:

The remote host closed the connection. The error code is 0x800704CD

Now, I'm fairly sure the user never sees this error, but my logs are full of them and I just want rid of it!

Clicking on a link on my page links to a controller action that builds the pdf. Here is the last part of the code for that:

        HttpContext.Current.Response.Clear();
        HttpContext.Current.Response.ContentType = "application/pdf";
        HttpContext.Current.Response.AddHeader("content-disposition", "attachment; filename=filename.pdf");
        HttpContext.Current.Response.BinaryWrite(stream.ToArray());
        HttpContext.Current.Response.Flush();
        stream.Close();
        HttpContext.Current.Response.End();

        Return View();

I think it's the Response.End() that is throwing the error because the action is trying to proceed after the response has ended. Does that sound correct? If so, is there anything I can do to prevent it?

Even though the user doesn't see the error, I see it and it must be solved!

Thanks - let me know if you need more info

c#
asp.net-mvc-3
asked on Stack Overflow May 30, 2013 by e-on

1 Answer

1

I recommend using the FileResult type to return the file content. Here's a link to the MSDN documentation: http://msdn.microsoft.com/en-us/library/system.web.mvc.fileresult(v=vs.98).aspx

To answer your question, Response.End causes the thread to immediately abort and any code that tries to run after that will throw an exception on the server side. Since the response has already been delivered to the client, it would only appear in logs.

Manipulation of the raw Response object is generally frowned upon in MVC, since that bypasses the magical underpinnings of the framework.

Populating a FileResult will allow you to perform your work, provide the file content as a stream and name the downloaded file. Once you've populated the desired properties, just return the FileResult instead of returning View().

answered on Stack Overflow May 30, 2013 by kilsek • edited May 30, 2013 by kilsek

User contributions licensed under CC BY-SA 3.0