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

Posted on 2008-11-11
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 and after I click the 'submit' button, the website says "The original link was: and your new link is" (Note, I appended the ID1.htm as an example. It can be anything. I don't care)

If I attempt now to go for example, I should be auto-redirected to

I'm VERY new to ASP (Classic, let alone nothing on 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 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


    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

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

    Write Comment

    Please enter a first name

    Please enter a last name

    We will never share this with anyone.

    Featured Post

    What Should I Do With This Threat Intelligence?

    Are you wondering if you actually need threat intelligence? The answer is yes. We explain the basics for creating useful threat intelligence.

    Suggested Solutions

    Sometimes in DotNetNuke module development you want to swap controls within the same module definition.  In doing this DNN (somewhat annoyingly) swaps the Skin and Container definitions to the default admin selections.  To get around this you need t…
    It was really hard time for me to get the understanding of Delegates in C#. I went through many websites and articles but I found them very clumsy. After going through those sites, I noted down the points in a easy way so here I am sharing that unde…
    Hi everyone! This is Experts Exchange customer support.  This quick video will show you how to change your primary email address.  If you have any questions, then please Write a Comment below!
    In this sixth video of the Xpdf series, we discuss and demonstrate the PDFtoPNG utility, which converts a multi-page PDF file to separate color, grayscale, or monochrome PNG files, creating one PNG file for each page in the PDF. It does this via a c…

    758 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

    Need Help in Real-Time?

    Connect with top rated Experts

    9 Experts available now in Live!

    Get 1:1 Help Now