Building a dynamic redirector (mask URL) using ASP or ASP.NET

Posted on 2008-11-11
Medium Priority
Last Modified: 2012-05-05

So here is the situation: I am trying to build a site that allows me to allow a user to type in a link and upon clicking submit, they are given a 'masked' link of the link they provided. So now, if the user goes to the 'masked' link, they are automatically redirected to the original link they provided.


I type in http://www.executiveboard.com/ and after I click the 'submit' button, the website says "The original link was: http://www.executiveboard.com/ and your new link is http://www.cebdata.com/ID1.htm" (Note, I appended the ID1.htm as an example. It can be anything. I don't care)

If I attempt now to go http://www.cebdata.com/ID1.htm for example, I should be auto-redirected to http://www.executiveboard.com/

I'm VERY new to ASP (Classic, let alone nothing on ASP.net) but I'm a very determined learner of the code and I don't mind the challenge. Just today I was able to figure out how to I can write to an access database and read from it using SQL.

While brainstorming....Is there a way to potentially store both the original and the new link in the table and once the user goes to the new link, it maybe hits the table, looks up the old link and goes to the original link? I can't seem to figure out if its possible to somehow tell any page that maybe ends in http://www.cebdata.com/ID# to look at the page. If this is NOT the way to do it, let me know and I'll be happy to learn what to do.

Lastly - I could do this manually by constantly creating a bunch of redirect pages but its going to clutter up the space on my server. I believe there HAS to be a way to do this. Please save me from this mess. Boss wants it in 48 hours and I want to exceed expectations by turning it in in 24 hours.

let me know your thoughts. Thanks!
Question by:piyushdabomb
LVL 29

Accepted Solution

Kumaraswamy R earned 2000 total points
ID: 22937580

Microsoft .NET Framework 2.0 come with limited URL Rewriting Library support and you have to write your own URL Rewriting engine if you need complex URL rewriting for your website.

The simplest URL Rewriting that you can achieve in seconds is by copy and paste the code below to your global.asax file.

void Application_BeginRequest(Object sender, EventArgs e)
 String strCurrentPath;
 String strCustomPath;
 strCurrentPath = Request.Path.ToLower();<BR>
 if (strCurrentPath.IndexOf("ID") >= 0)
  strCustomPath = "/Product10.aspx";  
  // rewrite the URL
  Context.RewritePath( strCustomPath );
As you can see from the code above, the URL Redirection is only limited to one rules. It will always redirect to one page called product10.aspx if it detects that your URL contains ID keyword.
Of course this one will not work if you want different Query String ID to redirect to different page or if you want to have different page redirection for different query string type.

To have a more complex URL Rewriting Rules, we can use Regular Expressions for implementing different redirection techniques.

Now, lets start writing some rules for your Redirection.

As you can see from the first rules above, It will redirect the URL from product/(Number).aspx into displayProduct.aspx?ID=(Number).
Second rules will redirect the URL if it Contains Items/Mouse/(Number).aspx into ViewItem.aspx?ID=(Number). You can add as many rules as you like by just adding the xml node above

   void Application_BeginRequest(Object sender, EventArgs e)
        string sPath = Context.Request.Path;        
        //To overcome Postback issues, stored the real URL.
        Context.Items["VirtualURL"] = sPath;
        Regex oReg;
        XmlDocument xmlDoc = new XmlDocument();
        _oRules = xmlDoc.DocumentElement;

        foreach (XmlNode oNode in _oRules.SelectNodes("rule"))
            oReg = new Regex(oNode.SelectSingleNode("url/text()").Value);
            Match oMatch = oReg.Match(sPath);

            if (oMatch.Success)
                sPath = oReg.Replace(sPath, oNode.SelectSingleNode("rewrite/text()").Value);
The code above is self explanatory. It will search from the rules in XML file and if it match, then it will rewrite the path.
Thats all you need to do to implement URL Rewriting. However after you rewrite the URL, all your page postbacks will not work.  The reason is because, ASP.NET will automatically by default output the "action" attribute of the markup to point back to the page it is on. The problem when using URL-Rewriting is that the URL that the page renders is not the original URL of the request . This means that when you do a postback to the server, the URL will not be your nice clean one.

To overcome this problem, you need to add this code on every page that you want to do postbacks.

    protected override void Render(HtmlTextWriter writer)
        if (HttpContext.Current.Items["VirtualURL"] != null)
            string sVirURL= HttpContext.Current.Items["VirtualURL"].ToString()
            RewriteFormHtmlTextWriter oWriter = new RewriteFormHtmlTextWriter(writer,sVirURL);
Source Code for RewriteFormHtmlTextWriter

public class RewriteFormHtmlTextWriter : HtmlTextWriter
    private bool inForm;
    private string _formAction;

    public RewriteFormHtmlTextWriter(System.IO.TextWriter writer):base(writer)

    public override void RenderBeginTag(string tagName)
        if (tagName.ToString().IndexOf("form") >= 0)
    public RewriteFormHtmlTextWriter(System.IO.TextWriter writer, string action)
        : base(writer)

        this._formAction = action;

    public override void WriteAttribute(string name, string value, bool fEncode)
        if (name == "action")
            value = _formAction;
        base.WriteAttribute(name, value, fEncode);

That's all you need to implement a complex and fully extensible URL Rewriting. You can create unlimited rules into your Rules.xml file and redirect to the page you want.


Author Comment

ID: 22939224
How do I use this? Where do I put all this? Can you give me some examples?

Featured Post

Free Tool: Site Down Detector

Helpful to verify reports of your own downtime, or to double check a downed website you are trying to access.

One of a set of tools we are providing to everyone as a way of saying thank you for being a part of the community.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

In an ASP.NET application, I faced some technical problems. In this article, I list them out and show the solutions that I found.  I hope it will be useful. Problem: After closing a pop-up window, the parent page should be refreshed automaticall…
User art_snob (http://www.experts-exchange.com/M_6114203.html) encountered strange behavior of Android Web browser on his Mobile Web site. It took a while to find the true cause. It happens so, that the Android Web browser (at least up to OS ver. 2.…
This lesson discusses how to use a Mainform + Subforms in Microsoft Access to find and enter data for payments on orders. The sample data comes from a custom shop that builds and sells movable storage structures that are delivered to your property. …
With just a little bit of  SQL and VBA, many doors open to cool things like synchronize a list box to display data relevant to other information on a form.  If you have never written code or looked at an SQL statement before, no problem! ...  give i…
Suggested Courses
Course of the Month14 days, 1 hour left to enroll

807 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question