CodeBetter.Com
CodeBetter.Com
RSS 2.0 via Feedburner
           Do you Twitter? Follow us @CodeBetter

Jeffrey Palermo (.com)

Blog moved to www.jeffreypalermo.com

How to do Url Rewriting with just an HttpHandler (without the side-effects) - level 400

If you are interested in doing Url Rewriting with an HttpHandler instead of an HttpModule, then this is the example for you.  Suppose you are deriving a piece of information from Url, like a product code.  To process it, you have a page that accepts the product code as a querystring variable.  Look at the code below for how you can present a friendly Url while abstracting that away from how you actually process the request.  You can do postbacks and everything, and the Url will never revert back to the "ugly" Url.
 

    public class ProductHandler: IHttpHandler, IRequiresSessionState

    {

        public bool IsReusable

        {

            get { return true; }

        }

 

        public void ProcessRequest(HttpContext context)

        {

            context.Items["originalQuerystring"] = context.Request.QueryString.ToString();
            context.Items[
"originalPathInfo"] = context.Request.PathInfo;

            string productCode = {some code to derive your product code};

            string page = "~/product.aspx";

            string queryString = "productCode=" + productCode;

            foreach(string key in context.Request.QueryString.Keys)

            {

                if(key != "productCode")

                {

                    queryString += string.Format("&{0}={1}", key, context.Request.QueryString[key]);

                }

            }

           

            context.RewritePath(context.Request.Path, string.Empty, queryString);

           

            Page hand = (Page)PageParser.GetCompiledPageInstance(page, context.Server.MapPath(page), context);

            // Listen for event to rewrite url back before the page renders.

            hand.PreRenderComplete += new EventHandler(hand_PreRenderComplete);

           

            hand.ProcessRequest(context);           

        }

 

        void hand_PreRenderComplete(object sender, EventArgs e)

        {

            HttpContext.Current.RewritePath(HttpContext.Current.Request.Path, 
               
HttpContext.Current.Items["originalPathInfo"].ToString(), 
               
HttpContext.Current.Items["originalQuerystring"].ToString());

        }

    }



Comments

Don Good said:

Another implimentation uses a HTTPHandler that inherits from IHttpHandlerFactory.

public class PageFactory : IHttpHandlerFactory
{
public IHttpHandler GetHandler(HttpContext context, string requestType, string url, string pathTranslated)
{
return PageParser.GetCompiledPageInstance(url, context.Server.MapPath("~/actualPage.aspx"), context);
}
}

URL ReWriting occurs before any template parsing, and also avoids "side effects".

Is there a difference in performance between the two, are there advantages of one over the other?
# August 10, 2005 7:28 PM

Jason Haley said:

# August 10, 2005 8:56 PM

Christopher Steen said:

"Source Server" - The best "Hidden" feature in Whidbey
Debugging [Via: Matt Pietrek ]
101 Code Samples...
# August 10, 2005 11:14 PM

Christopher Steen - Learning .NET said:

"Source Server" - The best "Hidden" feature in Whidbey Debugging [Via: Matt Pietrek ]
101 Code Samples...
# August 10, 2005 11:16 PM

Jeffrey Palermo said:

You can also use the PreRender event. The idea is that you trim off any querystrings you used for the request before the Page is rendered, so you don't want to tank the querystrings before Page or control code is finished with them.
# August 11, 2005 10:16 AM

Jeffrey Palermo said:

Don,
If you put your derived information in the Context.Items cache, then that would work just fine, but if you add those items to the querstring, which is very common, then you need a step to remove them from the querystring before rendering.
# August 11, 2005 10:17 AM

Wayne Larimore - his bloggin' Weighs said:

# August 11, 2005 3:09 PM

Wayne Larimore - his bloggin' Weighs said:

# August 11, 2005 3:09 PM

Link Blog said:

Jeffrey Palermo : How to do Url Rewriting with just an HttpHandler (without the side-effects) - level...
# August 11, 2005 5:34 PM

Daniel F said:

I like it, I like it a lot. Seems sneaky, but cool nonetheless.
# August 11, 2005 10:30 PM

Link Blog said:

Jeffrey Palermo : How to do Url Rewriting with just an HttpHandler (without the side-effects) - level...
# August 18, 2005 6:07 PM

Scott Sargent : Codeboy's Blog said:

I was trying to figure out the other day how to do url-rewriting on a handler basis, so I could key in

# January 25, 2007 1:19 PM

snickers said:

Wonderful!

# February 6, 2007 4:37 PM

kbird said:

Great! i was searching for this solution . stumpled on your sample , which solved my problem like sweet!

i was really scratching my head why context.RewritePath does not work for me , it litterelly returned blank pages for me.

would like to know what's wrong with context.RewritePath alone returns blank responses and why url rewrite needed before the page renders

thanks

# June 20, 2007 4:22 AM

sucharitha said:

i got a doubt regarding adding a http handler. In web.config where should i write

<add verb="Post"................./>.

and one more question regarding default handler

does it saves a file which is sent by client as http request into the specified folder?

# September 27, 2007 9:34 AM

About Jeffrey Palermo

Jeffrey Palermo is a software management consultant and the CTO of Headspring Systems in Austin, TX. Jeffrey specializes in Agile coaching and helps companies double the productivity of software teams. Jeffrey is an MCSD.Net , Microsoft MVP, Certified Scrummaster, Austin .Net User Group leader, AgileAustin board member, INETA speaker, INETA Membership Mentor, Christian, husband, father, motorcyclist, Eagle Scout, U.S. Army Veteran, and Texas A&M University graduate. Check out Devlicio.us!

Our Sponsors

Free Tech Publications

This Blog

Syndication

News

Headspring Systems

View Jeffrey Palermo's profile on LinkedIn

See my new blog at .jeffreypalermo.com