Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ApplicationInstance.CompleteRequest doesn't stop the execution of the code below it?

Tags:

asp.net

I was told that Respond.Redirect is an expensive process because it raises a ThreadAbortException. So instead, we should be using the CompleteRequest function instead. So I gave it a try but I noticed the codes below it still runs, which I do not want. I want to instantly force the browser to jump to another website.

Public Shared Sub TestCompleteRequest()
            If 1 = 1 Then
                System.Web.HttpContext.Current.Response.Redirect("Http://Google.com", False)
                System.Web.HttpContext.Current.ApplicationInstance.CompleteRequest()
            End If

            Throw New ApplicationException("Hello, why are you here?")
End Sub

As for the code above, the ApplicationException is still thrown. But why? :(

like image 485
Lasker Avatar asked Jun 29 '12 02:06

Lasker


2 Answers

Calling a method in the ASP.NET framework deals with the request, but the fact is you're still writing and running VB.NET - there's nothing in the language (nor should there be, I'd say) that indicates 'when this method returns, perform an Exit Sub'.

Who's to say you wouldn't want to execute some more of the method after telling ASP.NET to complete the request, anyway?

like image 119
AakashM Avatar answered Oct 26 '22 15:10

AakashM


One method doesn't replace the other directly. The CompleteRequest() method does not end execution when it's called. So if that's really what you want to do then Response.Redirect(string) would be the way to go.

CompleteRequest() simply bypasses the Response.End() method, which is what generates the ThreadAbortException you mentioned, but crucially CompleteRequest() flushes the response buffer. This means the HTTP 302 redirect response is sent to the browser at the line where you call CompleteRequest(), which gives you a chance to do operations that don't affect the response after it's been sent to the user.

The solution for you really depends on what you need to achieve, can you provide an example of what you're using Response.Redirect for and what other code is in the same method?

like image 16
greg84 Avatar answered Oct 26 '22 17:10

greg84