When is it safe to do Response.Redirect () without exception?

I have an intermediate class extending System.Web.UI.Page for all of my pages that require authentication. The class mainly performs user authentication.

When a user with insufficient access tries to visit a page, I try to redirect the user back to the login page, preventing any further page events from occurring (for example, Page_load). The first solution that came to mind was the default implementation of Response.Redirect. Of course, the disadvantage of this is the possibility of throwing ThreadAbortExceptions.

So my question is this: when (if at all) during the page life cycle is it safe to execute Response.Redirect () without the ThreadAbortException ever thrown?

public class CustomPage : System.Web.UI.Page
{
    protected override void OnInit(EventArgs e)
    {
        base.OnInit(e);
        if (!IsValid())
            Response.Redirect("login.aspx", true);
    }
}
+3
source share
3 answers

It is never "safe" if you pass true as the second parameter - it will always throw an exception. Internally Response.Redirect()invokes Response.End(), which immediately interrupts the current thread.

The only "safe" way to trim HttpRequestwithout exception is with HttpApplication.CompleteRequest(), but this will lead to further code execution in the current request.

+4
source

, ? , ( , FormsAuthentication , ).

web.config, , / . ASP.NET , , , .

+1

ThreadAbort, False endResponse. , , , .

If you are doing something really stupid like blocking, it is perfectly safe to throw a ThreadAbort exception on an ASP.NET page.

Another option is to use Server.Transfer. This has better performance than redirection, but also uses ThreadAbort exceptions.

0
source

Source: https://habr.com/ru/post/1739014/


All Articles