Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ASP.NET How To Stream File To User

Initially I was trying to figure out what the difference is between Response.Close and Response.End, but after doing more googling and research, its clear that I haven't seen a common way a Byte[] gets sent back to the client. I'll leave the code sample below, but I would like to know what the industry standard is for doing this.

Byte[] myBytes = GetReportBytes();
HttpContext.Current.Response.ClearContent();
HttpContext.Current.Response.AppendHeader("content-length", myBytes.Length.ToString());
HttpContext.Current.Response.AppendHeader("content-Disposition", "attachment;filename=" + this.ReportFileName + GetReportExtension());
HttpContext.Current.Response.ContentType = GetApplicationContentType();
HttpContext.Current.Response.BinaryWrite(myBytes);
HttpContext.Current.Response.Flush();
HttpContext.Current.Response.Close();
//CERT FIX
//HttpContext.Current.Response.End();
like image 229
RSolberg Avatar asked Apr 10 '09 00:04

RSolberg


1 Answers

I wouldn't call Response.Close() or Response.End().

Response.End() will stop the page execution/rendering at that point. No code following Response.End() will be run. The response is terminated at that point with no further output added to the stream.

Response.Close() is similar to Response.End(), but allows code to be executed after it is called (but no further output can be sent in the page response).

Response.Flush() will send any remaining response items to the page.

From an IIS core team member:

Response.Close sends a reset packet to the client and using it in anything other than error condition will lead to all sorts of problems - eg, if you are talking to a client with enough latency, the reset packet can cause any other response data buffered on the server, client or somewhere in between to be dropped.

In this particular case, compression involves looking for common patterns within the response and some amount of response has to be buffered by the compression code to increase the chance of finding longer repeating patterns - this part that is buffered cannot be sent to the client once you do Response.Close().

In short, do not use Response.Close().

like image 132
Mitch Wheat Avatar answered Sep 18 '22 00:09

Mitch Wheat