Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Html being added to Download file in response

I'm creating a csv file on the fly in my ASP.NET web app and sending it back to the user using the following code

ExportPlacementListPostModel postModel = CreatePostModelFromRequest();
MemoryStream stream = PlacementDatabaseController.ExportPlacementList(postModel);
Response.Clear();
Response.ClearContent();
Response.ClearHeaders();
Response.AddHeader("content-disposition", "attachment; filename=studentplacement.csv");
Response.ContentType = "application/octet-stream";
Response.BinaryWrite(stream.GetBuffer());

Every time I download the file the web pages html is being appended onto the document.

Can anyone see what i am doing wrong here.

Colin G

like image 947
pythonandchips Avatar asked Dec 02 '25 09:12

pythonandchips


2 Answers

Call Response.End() after Response.BinaryWrite to prevent further output being written to the response.

like image 81
pmarflee Avatar answered Dec 04 '25 00:12

pmarflee


HttpContext.Current.ApplicationInstance.CompleteRequest can be used as well.

The CompleteRequest method causes ASP.NET to bypass all events and filtering in the HTTP pipeline chain of execution and directly execute the EndRequest event.

The Response.End method ends the page execution and shifts the execution to the Application EndRequest event in the application's event pipeline. The line of code that follows Response.End is not executed.

Here's a good read: Don’t use Response.End() with OutputCache

like image 37
o.k.w Avatar answered Dec 03 '25 23:12

o.k.w



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!