When is it safe to do a Response.Redirect() without throwing an exception?
I have an intermediary class extending System.Web.UI.Page for all of my pages that require authentication. The class mostly does custom authentication handling.
When a user with insufficient access attempts to visit a page, I try to redirect the user back to the login page while preventing any further page开发者_开发知识库 events from being executed (ie. Page_load). The first solution that came to mind was the default implementation of Response.Redirect. Of course the downside to this is the possibility of ThreadAbortExceptions being thrown.
So my question is this: When (if at all) during the page life cycle is it actually safe to execute Response.Redirect() without ThreadAbortException ever being thrown?
public class CustomPage : System.Web.UI.Page
{
protected override void OnInit(EventArgs e)
{
base.OnInit(e);
if (!IsValid())
Response.Redirect("login.aspx", true);
}
}
It's never "safe" if you're passing true as the second parameter - it will always throw the exception. Internally, Response.Redirect()
calls Response.End()
, which directly aborts the current thread.
The only "safe" way to truncate an HttpRequest
without having an exception thrown is by using HttpApplication.CompleteRequest()
, but this will result in further code execution in the current request.
Curious, why are you doing this yourself? If anything, you should be using one of the authentication providers (ultimately, FormsAuthentication can be customized to handle almost any scenario you can think of).
Then, you can use the authorization element in your web.config file to indicate what pages/directories are not able to be accessed by anonymous users. ASP.NET will take care of the rest, redirecting the user to the login page you specify, as well as redirecting back when the user has logged in.
If you don't want a ThreadAbort exception you should pass False to the endResponse parameter. Of course this means you have to process the rest of the page, which is hard to get right.
Unless you are doing something really stupid like holding a lock, it is perfectly safe to throw a ThreadAbort exception in an ASP.NET page.
Another option is to use a Server.Transfer. This has better performance than a redirect, but it too uses ThreadAbort exceptions.
精彩评论