Fixing ThreadAbortException when using Response.End

I was working with code that allowed the user to save an Excel file by clicking on a link on a web page. The user was then prompted to open, save, or cancel the file. This little code snippet accomplishes this, the MyStream object being a MemoryStream object:

Response.ContentType = "application/";
Response.AddHeader("Content-Disposition", "ScottsCoolFile.xls");
Response.BinaryWrite(MyStream ().GetBuffer());

The problem with this code is that is throws a ThreadAbortException on the call to Response.End(). I don’t know about you, but this is not what I want happening. Exceptions = bad.

A little research led me to the HttpApplication.CompleteRequest method. So I replaced the last line of the code above, and I then had:

Response.ContentType = "application/";
Response.AddHeader("Content-Disposition", "ScottsCoolFile.xls");

Voila, same functionality, but no exception.

  1. #1 by Tim Golisch on January 30, 2012 - 5:44 pm

    Love it. +1 (if I could)

  2. #2 by Anders G. Nordby on August 23, 2012 - 12:51 pm

    Thank you, this really saved my day! You’ve no idea how long I searched for a solution before stumbling onto this blog post!

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s

%d bloggers like this: