Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Correct usage of Asp.Net Response.TransmitFile and Response.End()

Tags:

c#

asp.net

What is the correct usage of this code?

httpContext.Response.AddHeader("Content-Disposition", "inline; filename=" + HttpUtility.UrlPathEncode(fileName));
httpContext.Response.ContentType = "image/png";
httpContext.Response.AddHeader("Content-Length", new FileInfo(physicalFileName).Length.ToString());
httpContext.Response.TransmitFile(physicalFileName);
httpContext.Response.Flush();
httpContext.Response.End();  //Use it or not?

Is it really good to use .Flush() and .End()?

According to this you should never ever use Response.End() (only in error or hacking scenarios)

But in some of the answers the .End() is reconmended...?

Like in this article.

So it is appropriate to use Response.End or not?

like image 314
Markus Avatar asked Jan 28 '13 16:01

Markus


2 Answers

According to Thomas Marquardt, you should never use Response.End(). Instead you should use Context.ApplicationInstance.CompleteRequest(). Check this article as well, it's from Microsoft KB, recommending the use of Application.CompleteRequest() instead Response.End().

like image 180
Marcus Vinicius Avatar answered Sep 21 '22 18:09

Marcus Vinicius


I'm adding this so people don't fall into the mistaken accepted response: Response.End() might be required on most case scenarios after transmitting a file.

It doesn't matter if you use TransmitFile, or if you decided to write directly into the output stream, simply most of the times you want to ensure no one can write a single byte after you have sent a file.

This is specially important as there will be at some point a filter installed on IIS, a code on global asax EndRequest, or a developer that called your code and then did more things, and any of those will eventually append more stuff into the output stream without you noticing it, and it will corrupt your transmitted file contents. - CompleteRequest won't save you from this, as it allows adding more stuff in the response after you call it.

Response.End() is the only way to guarantee no other future code change or IIS filter will manipulate your response as intended.

like image 26
DanielCuadra Avatar answered Sep 22 '22 18:09

DanielCuadra