Easy way to automatically serve all ASP.NET web-form pages without the ".aspx" extension in URLs
The code in the "Application_Start" method of this Global.asax file will scan the web site root folder for .aspx files, and for each file setup a route mapping the file name without the extension, so that "http://example.com/example" will execute "http://example.com/example.aspx" etc.
The code in the "Application_BeginRequest" method will redirect any request (from old links etc.) for an .aspx file to the same url without the extension:
<%@ Application Language="VB" %>
<script runat="server">
Sub Application_Start(ByVal sender As Object, ByVal e As EventArgs)
'Enumerate .aspx files in root folder
For Each fn In System.IO.Directory.GetFiles(Server.MapPath("~/"), "*.aspx", IO.SearchOption.TopDirectoryOnly)
fn = fn.Substring(fn.LastIndexOf("\") + 1)
'Add route
System.Web.Routing.RouteTable.Routes.MapPageRoute(fn, fn.Substring(0, fn.Length - 5), "~/" & fn)
Next
End Sub
Sub Application_BeginRequest(ByVal sender As Object, ByVal e As EventArgs)
'Redirect any request for .aspx files to same name without the extension
Dim z = Request.RawUrl.Split("?"c)
If z(0).EndsWith(".aspx", StringComparison.InvariantCultureIgnoreCase) Then
'Only in root folder
If z(0).IndexOf("/", 1) < 0 Then
Response.RedirectPermanent(z(0).Substring(0, z(0).Length - 5) & If(z.Length > 1, "?" & z(1), ""))
End If
End If
End Sub
</script>