Question : Reading xml file in global.asax to redirect vanity url to correct page

I have created a xml file that has a vanity url and the redirect url. I want global asax to read this file to redirect the page request to the appropiate page. So for example if someone types in http://www.company.com/products have that be redirected to http://www.company.com/siteproducts/default.aspx. Below is some code I wrote.

<?xml version="1.0" encoding="utf-8" ?>
<redirectlinks>
  <link vanityurl="products" redirecturl="/siteproducts/default.aspx?WT.MC_ID=23" />
  <link vanityurl="compare" redirecturl="/siteproducts/default.aspx?WT.MC_ID=24" />
</redirectlinks>

global.asax

void Application_BeginRequest(object sender, EventArgs e)
     {  
        string strThisUrl;
        string strRedirectLink;
        XmlDocument doc = new XmlDocument();
        doc.Load(Server.MapPath("/redirects.xml"));
        XmlNodeReader nodeReader = new XmlNodeReader(doc);
        XmlReaderSettings settings = new XmlReaderSettings();
        settings.IgnoreComments = true;
        settings.IgnoreProcessingInstructions = true;
        settings.IgnoreWhitespace = true;
        XmlReader reader = XmlReader.Create(nodeReader, settings);
        while (reader.Read())
        {
            switch (reader.NodeType)
            {
                case XmlNodeType.Element:
                    strThisUrl = Request.Path.ToLower();
                    string newUrl = strThisUrl.Replace("/Default.aspx", "").Replace("/", "");
                    if (reader.Name == "link" && (reader.GetAttribute("vanityurl") == newUrl))
                    {
                        strRedirectLink = reader.GetAttribute("redirecturl");
                        Response.Redirect(strRedirectLink);

                    }
                    break;
            }

        }
    }

Any ideas on how to get this to work is greatly appreciated.

Answer : Reading xml file in global.asax to redirect vanity url to correct page

What you want is called a pipeline.  Here is a tutorial:
 http://www.nerdymusings.com/LPMArticle.asp?ID=12


I would take your code that parses the XML file and make that a standalone class.  And then store the values of the XML parsing as properties of the class.

That way the pipeline class just has to do this:

1:
2:
3:
4:
5:
6:
7:
8:
9:
10:
private void Application_BeginRequest(object Source, EventArgs e)
{
      HttpApplication oApp=(HttpApplication) Source;
      String strRequestUri = oApp.Request.Url.AbsoluteUri.ToLower();

      RedirectMap map =new RedirectMap();

      if (map.IsMapped(strRequestUri))
          oApp.Response.Redirect(map.GetRedirectUri(strRequestUri));
}
Random Solutions  
 
programming4us programming4us