Subscribe to this RSS feed
Home
About Me
Hire Me
Contact Me
Essays
Login
Downloads


The Tragically Hip :: www.thehip.com

Rush

Total Posts: 116


Context.RewritePath and the Global.asax file

I've always been fond of making my URL's clean and simple.  With that being said, URL variables are always useful.  But in the case of this site, I decided to clean up the URL's so it's very easy for people to find content.  To do this, I added the code:
void Application_BeginRequest(object sender, EventArgs e)
{
    HttpContext context = HttpContext.Current;
    string path = context.Request.Path;

    if (path.Contains(".aspx"))
    {
        if (path.ToLower().Contains("/article/"))
        {
            string id 
= path.Remove(0, path.LastIndexOf("/") + 1).Replace(".aspx", ""); try { int.Parse(id); context.RewritePath("~/article/article.aspx?ArticleID=" + id); } catch { // don't do anything because it's a postback } } } }

It's fairly simple to follow. First, I checked to see if it was an ASPX page, so I can weed out all the HTTP Handlers being used. Then I checked if it's a page I want to manipulate. Essentially, what Context.RewritePath does is take the incoming URL and modify it before it hits the page handler. So when I go to /Article/3.aspx, the code see's that it contain's both '.apsx' and 'article', and then because I know the format, I am stripping off everything else and keeping the article ID. Once that is done I pass the ID to the page that actually get's called behind the scenes. It's a quick and dirty way to make URL's human-friendly.


Tags:
Written by Steve Syfuhs on 12/2/2008 4:06:00 PM | Views: 1900

Comments
Copyright 2008 Steve Syfuhs