ApplicationInstance.CompleteRequest doesn't st

2020-07-06 02:14发布

问题:

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? :(

回答1:

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?



回答2:

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?



标签: asp.net