Sunday, February 24, 2008

URL Rewriting in ASP.NET

The first step in creating any HttpModule is creating the class that implements the IHttpModule interfaces. Start up Visual Studio .NET, create a new C# Web application ("Rewrite.Test"), and then add a new C# Class library named "Rewrite.NET" to the same solution. Create the new Web application first so that we can use that application to test the HttpModule and not break any other portion of the site.
I have renamed the default "Class1" to "Rewrite". Figure 1.1 below is its full source. (Don't forget to add the reference to System.Web in the class library).
Figure 1.1.1 Rewrite.cs Source Listing
using System;
namespace Rewrite.NET {
public class Rewrite : System.Web.IHttpModule {
///
/// Init is required from the IHttpModule interface
///
///
public void Init(System.Web.HttpApplication Appl) {
//make sure to wire up to BeginRequest
Appl.BeginRequest+=new System.EventHandler(Rewrite_BeginRequest);
}
///
/// Dispose is required from the IHttpModule interface
///
public void Dispose() {
//make sure you clean up after yourself
}
///
/// To handle the starting of the incoming request
///
///
///
public void Rewrite_BeginRequest(object sender, System.EventArgs args) {
//process rules here
}
}
}
There really isn't anything new in this block of code. Note, however, that I have trapped only the BeginRequest within the Init() method. The Rewrite_BeginRequest is where we will implement our rules engine.
At this step, take time to make the necessary modifications to the Web.config file so ASP.NET will know about the new handler. Figure 1.1.2 below shows the changes made to the Web.config file in the "Rewrite.Test" ap
Web.config



httpModules>
system.web>
xml version="1.0" encoding="utf-8" ?>




sectionGroup>
configSections>



SimpleSettings>
Rewrite.NET>
public void Rewrite_BeginRequest(object sender, System.EventArgs args) {
//process rules here
//cast the sender to an HttpApplication object
System.Web.HttpApplication Appl=(System.Web.HttpApplication)sender;
//load the settings in
System.Collections.Specialized.NameValueCollection SimpleSettings = (System.Collections.Specialized.NameValueCollection)System.Configuration.ConfigurationSettings.GetConfig("Rewrite.NET/SimpleSettings");
//see if we have a match
for(int x=0;x
string source=SimpleSettings.GetKey(x);
string dest = SimpleSettings.Get(x);
if(Appl.Request.Path.ToLower() == source.ToLower()) {
SendToNewUrl(dest, Appl);
break;
}
}
}
public void SendToNewUrl(string url, System.Web.HttpApplication Appl) {
Appl.Context.RewritePath(url);
}
------------------------------
More details click http://15seconds.com/Issue/030522.htm

plication.

No comments: