Home
 Index > ASP.NET Web Applications > Simple Method to Rewrite the URL

ASP.NET Web Applications:  URL Rewriting

Simple Method to Rewrite the URL

Re-write URLs without creating a module or using ISAPI filters.

Added on 3 Jun 2008

General Solutions:

Solution Summary:
Rewrite URLs in the Application_BeginRequest event in the Global.asax file.
Solution Details:

The code that follows takes a URL, finds the page type and ID in the URL and  rewrites the URL to serve up a page that takes Querystrings as parameters.

The original URL would looks something like this: http://www.site.com/List/Dotnet/102938/Rewrite_URL_Method.aspx

The following method would extraxt the ID (102938 in the above URL) and the type (if it is either "LIst" or "Details") and serve up the appropriate page -- in this case "content_list.aspx". 

Note that the "Dotnet" directory and the "Rewrite_URL_Method.aspx" page referenced in the above URL are completely ignored as there is neither such a directory or page by those names.

Sub Application_BeginRequest(ByVal sender As Object, ByVal e As EventArgs)
    
Dim stripped As String
     Dim strReqURL As String
    
Dim strCustomPath As String

    
strReqURL = Request.Path
     strReqURL = strReqURL.ToLower()

    
Dim bList As Boolean = (strReqURL.IndexOf("/list/") > -1)
    
Dim bDetails As Boolean = (strReqURL.IndexOf("/details/") > -1

     If bList Or bDetails Then

         
Dim key As Int32 = 0
          Dim file As String = "~/content/"
          stripped = strReqURL.Substring(0, strReqURL.LastIndexOf("/"))

               If stripped.LastIndexOf("/") > -1 Then
                   
stripped = stripped.Substring(stripped.LastIndexOf("/") + 1)
                   
If IsNumeric(stripped) Then
                        
key = stripped
                   
End If
               
End If

               If bList Then
                   
file &= "content_list.aspx"
               
ElseIf bDetails Then
                   
file &= "content_details.aspx"
               
End If

          Context.RewritePath(file & "?id=" & key)

     End If

End Sub

 

An alternative to having the ID in the URL would be to query a database.  You can provide a "filename" and search a database based on this faux filename assuming, of course, that these names are unique.

Other more complex  samples for Rewriting URLs are readilly found on the Internet, usually involving creation of a module.

Was this solution useful? Yes No Added on 3 Jun 2008
Rating: 

Copyright 2010 © E-Centric, Inc. | Terms of Use