Articles → .NET → URL Rewriting Using HTTPModules In .Net
URL Rewriting Using HTTPModules In .Net
- Visual studio installed on your machine.
- Have the hands on experience in creating web application.
- Have knowledge of HTTP modules.
- Create a web application and name it say URLRewriting.
- Add a class and inherit the class with IHttpModule interface.
public class UrlRewriter : IHttpModule{}
- Now the class has implemented the IHttpModule interface then the class must implement 2 methods Init and Dispose.
public void Dispose() {}
public void Init(HttpApplication app) {}
- In this init method add an event handler and name it let us say Rewrite_BeginRequest. So the definition of Init function would be
public void Init(HttpApplication app) {
app.BeginRequest += new EventHandler(Rewrite_BeginRequest);
}
void Rewrite_BeginRequest(object sender, EventArgs e) {}
- When you create a web application a file default.aspx is created in it. Now add another file called Default2.aspx(you can name anything you want).
- Add a 2 buttons in Default.aspx.
- On button click event add the following code.
protected void Button1_Click(object sender, EventArgs e) {
Response.Redirect("Admin");
}
protected void Button2_Click(object sender, EventArgs e) {
Response.Redirect("Contact");
}
- Now go back to UrlRewriter class and add code to Rewrite_BeginRequest event. So the code would be
void Rewrite_BeginRequest(object sender, EventArgs e) {
HttpApplication appObject = (HttpApplication) sender;
HttpContext contextObject = appObject.Context;
string path = contextObject.Request.Url.AbsoluteUri;
if (!path.EndsWith(".aspx")) {
path = path.Split('/')[path.Split('/').Length - 1];
contextObject.RewritePath("Default2.aspx?module=" + path);
}
}
- Now it is the time to register the HTTPmodule in web.config file. Add the following code in web.config file.
<httpModules>
<add name="rewriter" type="CustomClass" />
</httpModules>
- On default2.aspx write the following code
protected void Page_Load(object sender, EventArgs e) {
if (!IsPostBack) {
string module = Request["module"].ToString();
Response.Write(String.Format("You have entered {0} module", module));
}
}
Click to Enlarge