Default pages are convenient in many cases as users can just go to a site without having to remember page names (sometimes they are case-sensitive!)  Yet, ASP.NET has an issue handling default pages when it comes to postback.  For example, when a button click is fired, the event is never caught in the back-end when the page is visited without its page name (i.e, http://foo/bar instead of http://foo/bar/Default.aspx)

To get around to this is not difficult, simply redirect users to the URL with page name explicitly, for example


protected void Page_Load(object sender, EventArgs e)

{

string defaultPage = "default.aspx";

string rawUrl = Request.RawUrl;

if (rawUrl.ToLower().IndexOf(defaultPage) < 0)

{

string newUrl;

if ( rawUrl.IndexOf("?") >= 0)

{

// URL contains query string

string[] urlParts = rawUrl.Split("?".ToCharArray(), 2);

newUrl = urlParts[0] + defaultPage + "?" + urlParts[1];

}

else

{

newUrl = (rawUrl.EndsWith("/")) ? rawUrl + defaultPage : rawUrl + "/" + defaultPage;

}

Response.Redirect(newUrl);

}

}

Advertisements