Application BeginRequest Code in Global.asax for URL Rewriting
2/16/2006 11:56:41 AM
This code is will let you get a glimpse of a URL rewriting engine. There are those of us that don't have the luxury of being able to host our own sites. If you have any questions or can see any way to make this more efficient please let me know.
The Application_BeginRequest section is an ideal location because like the name specifies, this is the first event in the HTTP pipeline chain of execution. When using a Global.asax file, every ASP.NET request response will first start here.
In this code you will noticed the NameValueCollection called blogConfig. Keep in mind that this code was taken from my own application. I happen to keep the path of entry.aspx in an XML configuration file. This is a very easy change to make. Just comment out the blogConfig declaration and change strEntryPath to equal the location of your entry / employee / product / article / etc... ASPX file.
The Regular Expression in strPattern will return a result for the following URL schemas:
http://www.domain.com/stories/archive/story_about_this_444.aspx
http://www.domain.com/blog/210.aspx
http://www.domain.com/hey_this_works_too_post_00222.aspx
The ID's that are picked up will be 444, 210, and 222.
Global.asax
Sub Application_BeginRequest(ByVal sender as Object, ByVal e as EventArgs)
Dim httpContext As System.Web.HttpContext = httpContext.Current()
Dim currentURL As String
Dim strPattern As String = "000(\d+).aspx"
If Request.QueryString("entryID") > 0 Then
currentURL = "000" & Request.QueryString("entryID") & ".aspx"
Else
currentURL = Request.Path.ToLower()
End If
Dim blogConfig As NameValueCollection
blogConifg = ConfigurationSettings.GetConfig("settings/blogConfig")
Dim strEntryPath As String
If blogConfig("entryPath") = "" Then
Response.Write("Please add blog path to configuration file")
Return
Else
strEntryPath = blogConfig("entryPath").ToString()
Dim objRegEx As Regex
Dim Matches As MatchCollection
Dim pageID As String
objRegEx = New Regex(strPattern, RegexOptions.IgnorePatternWhitespace)
Matches = objRegEx.Matches(currentURL)
If Matches.Count > 0 Then
pageID = Matches(0).Groups(1).ToString()
httpContext.RewritePath(strEntryPath & "?entryID=" & pageID)
Else
httpContext.RewritePath(currentURL)
End If
End If
End Sub
All that's left to do now is programmatically create static URL's. What I did was run a replace function on my post title stripping illegal characters away and then concatenating the entryID to the end and add .aspx.
Please feel free to e-mail me or post questions relating to this matter and I will try my best to answer them.
Happy programming!
Code,
VB.NET
