Dymanic URL Mapping in Dotnet - VB Code

by rlynch April 21, 2010 06:01
The wonderfull world of SEO tends to frown on query string arguments and will actually almost penalize you for using them. Due to that it is often preferable to change your urls to have a more SEO friendly look.

e.g. http://lynchtek.com/examples.aspx?id=30989&cat=sql is not as user friendly as http://lynchtek.com/sql/script_to_generate_aspnet _db
So.. how do we go about building urls like the second example. Enter ULR mapping (remapping). In one example at 4guysfromrolla (a great site by the way) - Scott G. showed how to do this in the global.asax file. However he also promoted not taking this approch due to difficult to implement code with .. (Interesting).
Step in alternative 2.. Build a class that handles the remapping and add the class as a handler in your web.config file.. then just read the query string argument in your remapped page to figure out what the arguments were. (Sounds complex, but is really very easy to implement as we will see here.)
First lets look at sample code (that should be in your app_code direcotry) for the purpose of making it easy to follow, i have called the directory that will handle the querystring 'rewritedir', but it can be anyting from empolyees to products.
This class must implement the IHttpModule. Due to that it also needs to have all the method signatures included. The important one here is the method OnBeginRequest method.

Imports Microsoft.VisualBasic
Imports System.Data.SqlClient
Public Class UrlRewrite
Implements IHttpModule

Public Sub Dispose() Implements System.Web.IHttpModule.Dispose

End Sub

Public Sub Init(ByVal context As System.Web.HttpApplication) Implements System.Web.IHttpModule.Init
AddHandler context.BeginRequest, AddressOf OnBeginRequest
End Sub

Private Sub OnBeginRequest(ByVal sender As Object, ByVal e As EventArgs)
Dim app As HttpApplication
app =
CType(sender, HttpApplication)

' Test to see if this is a directory that we are supposed to be mapping to a query string.
If app.Request.RawUrl.ToString.IndexOf("/rewritedir/") > -1 Then
'Grab the part of the path after the direcoty name..
Dim path As String = app.Request.RawUrl.ToString.Substring(app.Request.RawUrl.ToString.IndexOf("rewritedir") + 11)
'If you webserver doesn't forward requests for a wildcard to the asp.net engine
'you will probably have needed to add the .aspx extension to the link.
'because you don't want that in the query string strip off the extension
'and add it to the page in your rewrite direcotry that processes dynamic querys.
'Note any .aspx page in this directory will fail to run. (also do not use images in here)
app.Context.RewritePath("default.aspx", "", path.Replace(".aspx", ""))
End If

End Sub

End
Class

In the onBeginReqest Event we test to see if the request is targeting a url that contains the directory name that our dynamic content is generated from. It is important here to note that there can only be a single active page inside this directory as with the event it basically redirects any url content into the query string arguments for the page that handles the active content.

One common strategy in webdevelopment now is to omit the extension of your webpages as it allows you to change your technologies at will, without breaking links. E.G. we can move from .aspx to .chm or .php (dont ask me why you would want to: diamond rings).
However in certain hosting situations this will not be possible as there is no wild card mapping that will direct a directory request to the onBeginRequest event. For that reason in my sample card a replace on the path is being done to remove the request for a .aspx page and turn that into the arguments that get sent to the page.
Realizing that where you may have mulitple parameters it is very important to construct your path to the query correctly.
e.g. sport/state/age   or category/subcategory/brand  - this is because the argumnents you send to the page that handles the request need to be parsed from your url.
So. for
           http://lynchtek.com/tipsandtricks/sql/configuringsecurity/logins it could realiably map that url to
Quick breakdown  app.Context.RewritePath("default.aspx", "", path.Replace(".aspx", ""))
The first argument is the page/handler in the tipsandtricks directory of the above link (or in the example the "rewritedir" direcotry)
the second argument is pathinfo in this situation we are telling it to use the current directory
the third argument is the querystring - where you have multiple arguments you can use the strings "split" method to seprate the arguments out into an array and then build the arguments based on it values position in the array.
Ok so that is the handler.. Now it is time to wire this in to your website. This is done by adding a line into the web.config. This entry must be placed in the system.web section and in the <system.web>  element and specifically the <httpModules> subelement
WEB.CONFIG
E.G.

<httpModules>

<add name="UrlRewrite" type="UrlRewrite"/>

<add name="ScriptModule" type="System.Web.Handlers.ScriptModule, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"/>

</httpModules>

In the above example it is telling the asp.net process to include the class UrlRewrite as a module, and because it imports the IHttpModule the code will then intercept any request for a webpage.
Lastly we need to wire in our default.aspx page to process the querystring. (Nothing special here if you have used querystring arguments before.) This should be done in the page_load event. The page load will then look at your querystring and from it send a query dynamically to your database.
E.G. 

Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load

ds = getData(Request.QueryString().ToString)

rptrMenu.DataSource = ds.Tables(0)

rptrMenu.DataBind()

rptrThumbs.DataSource = ds.Tables(1)

rptrThumbs.DataBind()

End Sub


The last part of your puzzle is building a menu dymamically from a database. Again this should be reasonably straight forward to any SQL guru and you could use any number of dotnet controls to populate your menu. Due to the light weight nature of the <asp:repeater /> control it is my favorite mechinisim. Utilizing divs, spans, ul, li's etc you can build nice xmtml/css based menu's and get rid of a bunch of bad asp.net generated *&&^$. Due to its extreem flexibility another tool you can utilize is JQuery to provide some really nice effects for you users.

An example for building a menu from the repeater and css (taking advantage of the code developed at www.purecssmenu.com - a very cool free menu generateor...)
Code for webpage - a quick word of warning if the category or menu uses a "/" make sure you replace it with an _ or the split funciton will assume it to be another directory(argument)..
I have found that having a "menu" column in the database to be very usefull to avoid unplesant surprises. (also a good idea to avoid spaces and other special characters when choosing the link name.)


 

Currently rated 5.0 by 1 people

  • Currently 5/5 Stars.
  • 1
  • 2
  • 3
  • 4
  • 5

Tags:

asp.net | CSS | DotNet Utilities | SQL Server

Comments

Add comment


(Will show your Gravatar icon)  

  Country flag

biuquote
  • Comment
  • Preview
Loading



Powered by BlogEngine.NET 1.4.5.0
Theme by Mads Kristensen | Modified by Mooglegiant

Calendar

<<  September 2010  >>
MoTuWeThFrSaSu
303112345
6789101112
13141516171819
20212223242526
27282930123
45678910

View posts in large calendar