Thursday, October 6, 2016

URLRewriting in the land of Global.asax

Earlier I wrote about using URLRewriter.net. It's a decent piece of software, but has some serious drawbacks, especially since it forces you to modify the IIS configuration for a specific website. As a webmaster, trying to keep that straight on 1500+ websites isn't exactly an ideal solution. So today, I'm going to present you with a fairly basic method in this case of handling it in the global.asax file. This method is handled inside the Application_BeginRequest Subroutine.


Dim incoming As HttpContext = HttpContext.Current
Dim oldpath As String = incoming.Request.Path.ToLower()
Dim pageid As String
Dim DynamicPageName As String
Dim BareName As String
Dim regex As System.Text.RegularExpressions.Regex
Dim matches As MatchCollection
'------------------------------------------------
' URL rewriter for WebPage.aspx?pageid=xxx
'------------------------------------------------
' set unique page name for dynamic pages in web.config
DynamicPageName = ConfigurationManager.AppSettings("cfgWebPageName")
' get the bare name for moving pageid in the string
BareName = RemoveFileExtension(DynamicPageName)


Here is the RemoveFileExtension function. We can't use the Path.GetFilenamewithoutExtension function because of the potential case for a QueryString at the end of a dynamic page:


Function RemoveFileExtension(ByVal parmFileName as String) as String
   Dim FullLength as Integer = parmFileName.Length
   Dim RightStringToCut as String = parmFileName.Substring(parmFileName.LastIndexOf("."))
   Dim RightLength as Integer = RightStringToCut.Length
   Dim NewStringLength as Integer = FullLength - RightLength
   Dim NewWebPageName as String = parmFileName.Substring(0, NewStringLength)
   Return NewWebPageName
End Function


Now onto the rest of our application...


regex = new System.Text.RegularExpressions.Regex(BareName & "(\d+).aspx", RegexOptions.IgnoreCase Or RegexOptions.IgnorePatternWhitespace)
matches = regex.Matches(oldpath)
If matches.Count > 0 Then
   pageid = matches(0).Groups(1).ToString()
   incoming.RewritePath(DynamicPageName & "?pageid=" + pageid)
Else
   incoming.RewritePath(oldpath)
End If


In the above code, it is specifically looking for a page named "webpageNN.aspx" where NN is equal to the page ID. So the page would be labeled as webpage18.aspx. It then rewrites the URL to webpage.aspx?pageid=18. The user, searchengines, etc. still see webpage18.aspx though. Easily enough, this could be expanded to be used with more friendly URLs, such as mywedding.aspx which would rewrite to webpage.aspx?pageid=18 via the addition of database information.

No comments: