18

What are the advantage and disadvantage for each of Response.End() and CompleteRequest()? Where should I and should I not use them? I looked at this question but I didn't get a proper answer.

Dale K
  • 25,246
  • 15
  • 42
  • 71
Raed Alsaleh
  • 1,581
  • 9
  • 27
  • 50

1 Answers1

37

HttpResponse.End flushes the output buffer to the client and terminates the current request-handling thread (this is bad), whereas HttpApplication.CompleteRequest tells ASP.NET to immediately skip all future stages in the ASP.NET pipeline and jump directly to the EndRequest step (which also raises the HttpApplication.EndRequest event). The request thread then proceeds with normal end-of-life cleanup.

So, Response.End is like an ejector seat: it quickly ends things, but means you lose control and might be unnecessarily harsh. Whereas CompleteRequest is like making an emergency landing at the nearest airport.

Dai
  • 141,631
  • 28
  • 261
  • 374
  • So when I must use Response.End() and When I must use HttpApplication.CompleteRequest() – Raed Alsaleh Mar 28 '13 at 08:01
  • 5
    Ideally, you'd never need to use either. – Dai Mar 28 '13 at 19:48
  • 5
    Read [Correct use of System.Web.HttpResponse.Redirect](http://blogs.msdn.com/b/tmarq/archive/2009/06/25/correct-use-of-system-web-httpresponse-redirect.aspx) - `Response.End` is a risky "ejector seat" ... use with **utmost** caution... – marc_s Aug 21 '14 at 19:43
  • That's exactly what I need, an ejector seat, but I can't find that method anywhere – nuander Sep 08 '16 at 14:24
  • @nuander are you using WebAPI, ASP.NET Core or MVC 6? They radically changed the ASP.NET API in those releases. – Dai Sep 08 '16 at 15:28
  • Can I assume then it's also a bad idea to call either one when writing your own iHttpHandler? – Brain2000 Jun 13 '18 at 00:19
  • 2
    @Dai If the use of HttpApplication.CompleteRequest is not recommended, then how to do proper redirection ? Isn't the Response.Redirect(url, false); followed by Context.ApplicationInstance.CompleteRequest(); proper way ? – Jay Shah Dec 17 '18 at 21:11
  • @JayShah In the context of a Redirection-response, using `CompleteRequest` _might_ be correct - provided that you don't have any other code in the request pipeline that needs to run. That said (and without knowing more about your use-case) I wouldn't necessarily recommend using `CompleteRequest`, especially in a WebForms `.aspx` `Page` handler, where some view cleanup and session-management code probably should be run instead of skipped-over. FWIW (and as far as I can remember) I've never _needed_ to use `CompleteRequest` with `Response.Redirect` in ASP.NET 4.x. – Dai Mar 14 '23 at 00:49