Search code examples
c#asp.netresponseepplus

Response.End causing System.Threading.ThreadAbortException


I have a try catch in a button_Click() method where I use EPPlus to save some data to an Excel spreadsheet.

try 
{
 .... Some calculations here...
   //Create Excel output.
                Response.Clear();
                Response.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
                Response.AddHeader("content-disposition", "attachment;  filename=Report " +
                                   DateTime.Today.Day.ToString() + "-" + DateTime.Today.Month.ToString() + "-" +
                                   DateTime.Today.Year.ToString() + " " + DateTime.Now.Hour + "-" +
                                   DateTime.Now.Minute + "-" + DateTime.Now.Second + ".xlsx");
                package.SaveAs(Response.OutputStream);
                Response.End();
}

cach()
{
   LogException();
}

I get an error System.Threading.ThreadAbortException, which I get because of Response.End() above, I get that.

What is really annoying is that despite that on my dev machine it still outputs the file but when I place the website on the server, it logs the error, the page keeps loading infinitely and never spits out the file.

Anyone have an idea what is going wrong there?


Solution

  • Just catch ThreadAbortException and do nothing. You can safely ignore this exception.

    EDIT: Get rid of the log, or add a check to not log on ThreadAbortException

    catch(Exception ex){
        if (ex is System.Threading.ThreadAbortException)
        {
            //do nothing
            return;
        }else{
            LogException(ex);
        }
    }