File not downloaded when Response.End() is replaced by ApplicationInstance.CompleteRequest()

681 Views Asked by At

I would like to create a file download. Here is the original code for it:

Response.Clear()
Response.ContentType = "text/html"
Response.AddHeader("Content-Disposition", String.Format("attachment; filename=""Dashboard_{0}.html""", time))
Response.Write(html)
Response.End()

It looked okay. File was downloaded normally, but I found the below message in Output.

A first chance exception of type 'System.Threading.ThreadAbortException' occurred in mscorlib.dll

I have tried to search for solutions of how to fix this exception, and I saw everyone talking about replacing Response.End() with HttpContext.Current.ApplicationInstance.CompleteRequest().

When I tried it, the exception no longer occurred, but the outcome was even worse - file not downloaded after the change. It was same as if I just remove Response.End() and add nothing.

In such case, what should I do to get rid of the exception when downloading needs to occur? Or should I just ignore the exception since it does not seem to create any unfavourable outcome?

1

There are 1 best solutions below

0
Shantanu On

Here response.End()

To mimic the behavior of the End method in ASP, this method tries to raise a [ThreadAbortException] exception.

Please take a look at this https://learn.microsoft.com/en-us/dotnet/api/system.web.httpresponse.end?redirectedfrom=MSDN&view=netframework-4.8#System_Web_HttpResponse_End

also try removing

Response.Clear()