Knoxville, TN

ASP.Net: URL Rewriting and Login forms

June 10, 2007

Here’s a quirk I’ve been stuck on for a while in the process of rewriting this site in ASP.Net, and just recently figured out a workaround for.

When you’re doing any sort of URL rewriting with Context.RewritePath, all of your pages post back to their actual URL instead of the URL that the user requested. While this is fine if you’re simply redirecting because you changed the name of a file, it’s not so nice if you’re actually using this as the basis for your content management system. Which I do.

First off, if you’re doing any sort of URL rewriting, check ScottGu’s blog post on the subject–pay particular attention to the “Handling ASP.Net Postbacks with URL Rewriting.” This will clear up most problems you have with forms on your pages.

There are, however, a few quirks with the Login and LoginStatus controls (used with ASP.Net 2.0’s built-in membership system) that this won’t fix.

To make a functional login button, capture the original URL before rewriting, and then set the Login control’s DestinationPageUrl property to the originally requested URL.

To make a functional logout button, capture the original URL before rewriting. Set the LoginStatus’ LogoutAction property to Redirect, and the LogoutPageUrl property to the original URL.

Here’s an example of how I did it:

if (!Context.User.Identity.IsAuthenticated)
{
    ((Login)LoginView1.FindControl("LoginForm1")).DestinationPageUrl = originalUrl;
    ((LinkButton)LoginView1.FindControl("LoginForm1").FindControl("LoginButton")).PostBackUrl = originalUrl;
}
else
{
    ((LoginStatus)LoginView1.FindControl("LoginStatus1")).LogoutPageUrl = originalUrl;
}
×