Tuesday, 26 July 2011

Rewriting a URL on-the-fly using ASP.NET 2.0 and VB.NET


This tutorial shows you how to rewrite URL paths on-the-fly using ASP.NET 2.0 and VB .NET.

In some instances you may want to rewrite a URL on-the-fly in ASP.NET. This is done in the Global.asax file which contains event handlers for major events like Application_Start and Session_Start. This file is located in the root of the application directory and handles application level logic that doesnt interact with or create UI objects. In this example, we will be writing code for the Application_BeginRequest to rewrite the URL before any resource or URL is activated in the application.

To perform any kind of advanced URL rewriting you will need to use the RegularExpression class objects found in System.Text.RegularExpressions.

Whenever a new HTTP request starts the Application_BeginRequest() event fires and we grab the current request in a HTTPContext object.

Dim myContext As HttpContext = HttpContext.Current

We used over 10 web hosting companies before we found Server Intellect. Their dedicated servers and add-ons were setup swiftly, in less than 24 hours. We were able to confirm our order over the phone. They respond to our inquiries within an hour. Server Intellect's customer support and assistance are the best we've ever experienced.

By accessing the Request property of this object we can study an HttpRequest object and determine information commonly included in most HTTP requests (such as the URL requested). In this example, we want to redirect any request for "Default.aspx" and rewrite it to "Something.aspx". We start by creating a Regex object that will capture the appropriate text.

Dim rewrite_regex As Regex = New Regex("(.+)\/((.+)\.aspx)", RegexOptions.IgnoreCase)

Server Intellect assists companies of all sizes with their hosting needs by offering fully configured server solutions coupled with proactive server management services. Server Intellect specializes in providing complete internet-ready server solutions backed by their expert 24/365 proactive support team.

This regular expression has three capturing groups: the directory the file is in, the filename (without extension), and the filename (with extension). We test the last group (filename w/ extension) to make sure it matches "Default.aspx" before we use the RewritePath() function of our HttpRequest object and forward the user before any page has been loaded.

Try

'see if we need to rewrite the URL
Dim match_rewrite As Match = rewrite_regex.Match(myContext.Request.Path.ToString())

If match_rewrite.Groups(2).Captures(0).ToString() = "Default.aspx" Then

myContext.RewritePath("Something.aspx")

End If

Catch ex As Exception
Response.Write("ERR in Global.asax :" & ex.Message + Constants.vbLf + Constants.vbLf + ex.StackTrace.ToString() & Constants.vbLf + Constants.vbLf)

End Try

If you're looking for a really good web host, try Server Intellect - we found the setup procedure and control panel, very easy to adapt to and their IT team is awesome!

The flow for the entire Global.asax page is as follows. Some event stubs are created by default when adding a new Global.asax file via Visual Studios. These are included for completeness.

<%@ Application Language="VB" %>

<script runat="server">

Sub Application_Start(ByVal sender As Object, ByVal e As EventArgs)
' Code that runs on application startup
End Sub

Sub Application_End(ByVal sender As Object, ByVal e As EventArgs)
' Code that runs on application shutdown
End Sub

Sub Application_Error(ByVal sender As Object, ByVal e As EventArgs)
' Code that runs when an unhandled error occurs
End Sub

Sub Session_Start(ByVal sender As Object, ByVal e As EventArgs)
' Code that runs when a new session is started
End Sub

Sub Session_End(ByVal sender As Object, ByVal e As EventArgs)
' Code that runs when a session ends.
' Note: The Session_End event is raised only when the sessionstate mode
' is set to InProc in the Web.config file. If session mode is set to StateServer
' or SQLServer, the event is not raised.
End Sub

Protected Sub Application_BeginRequest(ByVal sender As Object, ByVal e As EventArgs)

Dim myContext As HttpContext = HttpContext.Current

Dim rewrite_regex As Regex = New Regex("(.+)\/((.+)\.aspx)", RegexOptions.IgnoreCase)

Try

'see if we need to rewrite the URL
Dim match_rewrite As Match = rewrite_regex.Match(myContext.Request.Path.ToString())

If match_rewrite.Groups(2).Captures(0).ToString() = "Default.aspx" Then

myContext.RewritePath("Something.aspx")

End If

Catch ex As Exception
Response.Write("ERR in Global.asax :" & ex.Message + Constants.vbLf + Constants.vbLf + ex.StackTrace.ToString() & Constants.vbLf + Constants.vbLf)

End Try

End Sub

</script>

Looking for the C#.NET 2005 Version? Click Here!

Looking for more ASP.NET Tutorials? Click Here!

No comments:

Post a Comment