Articles → .NET → URL Rewriting Using Httpmodules

URL Rewriting Using Httpmodules





  1. Visual studio installed on your machine.
  2. Have the hands on experience in creating web application.
  3. Have knowledge of HTTP modules.


  1. Create a web application and name it say URLRewriting.
  2. Add a class and inherit the class with IHttpModule interface.
  3. public class UrlRewriter : IHttpModule{}


  4. Now the class has implemented the IHttpModule interface then the class must implement 2 methods Init and Dispose.
  5. public void Dispose() {}
    public void Init(HttpApplication app) {}


  6. In this init method add an event handler and name it let us say Rewrite_BeginRequest. So the definition of Init function would be
  7. public void Init(HttpApplication app) {
      app.BeginRequest += new EventHandler(Rewrite_BeginRequest);
    }
    void Rewrite_BeginRequest(object sender, EventArgs e) {}


  8. 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).
  9. Add a 2 buttons in Default.aspx.
  10. On button click event add the following code.
  11. protected void Button1_Click(object sender, EventArgs e) {
      Response.Redirect("Admin");
    }
    protected void Button2_Click(object sender, EventArgs e) {
      Response.Redirect("Contact");
    }


  12. Now go back to UrlRewriter class and add code to Rewrite_BeginRequest event. So the code would be
  13. 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);
      }
    }




  14. Now it is the time to register the HTTPmodule in web.config file. Add the following code in web.config file.
  15. <httpModules>
    	<add name="rewriter" type="CustomClass" />
    </httpModules>


  16. On default2.aspx write the following code
  17. 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));
      }
    }






Picture showing the output of URL rewriting using HTTPModules
Click to Enlarge




Posted By  -  Karan Gupta
 
Posted On  -  Sunday, November 21, 2010

Query/Feedback


Your Email Id
 
Subject
 
Query/FeedbackCharacters remaining 250