Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Response.Redirect exception

Tags:

asp.net

Executing the line:

Response.Redirect("Whateva.aspx", true);

Results in:

A first chance exception of type 'System.Threading.ThreadAbortException' occurred in mscorlib.dll
An exception of type 'System.Threading.ThreadAbortException' occurred in mscorlib.dll but was not handled in user code

The exception is because of the "true" part, telling it to end the current request immediately.

Is this how it should be?
If we consider:

  • Exceptions are generally considered heavy, and many times the reason for ending the request early is to avoid processing the rest of the page.
  • Exceptions show up in performance monitoring, so monitoring the solution will show a false number of exceptions.

Is there an alternative way to achieve the same?

like image 890
Tedd Hansen Avatar asked Jan 04 '11 11:01

Tedd Hansen


2 Answers

You're right regarding the fact that the developer should avoid raising of (and catching) exceptions since the execution runtime consumes time and memory in order to gather the information about the particular exception. Instead he (or she) should simply not let them occur (when it's possible).

Regarding the Response.Redirect: this behavior is "by-design" but you might want to use a well-known workaround. Please read this KB article.

-- Pavel

like image 82
volpav Avatar answered Oct 11 '22 16:10

volpav


One approach I generally take in this scenario is to not end the response during the response, but to follow it immediately with a return (or other flow control). Something like this:

Response.Redirect("Whateva.aspx", false);
return;

This depends on where the redirect is taking place in your logic flow, of course. However you want to handle it is fine. But the idea is that, when you want to end the response on the redirect anyway, then exiting the method in question via a return isn't out of the question.

One approach I've seen people take in this matter quite often, and it should go without saying that this is to be avoided but for completeness I'm going to say it anyway (you never know who may stumble upon this question later via Google, etc.), is to catch and swallow the exception:

try
{
    Response.Redirect("Whateva.aspx", true);
}
catch (Exception ex)
{
    // do nothing
}

This, of course, should not be done, for a number of reasons. As I inferred from your description of exceptions, you undoubtedly already know that this would be bad practice. But, as I said, it's worth noting this fact in the answer.

like image 36
David Avatar answered Oct 11 '22 18:10

David