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?
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()
.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With