Jeffrey Palermo (.com)

Sponsors

The Lounge

News

Advertisement

Images in this post missing? We recently lost them in a site migration. We're working to restore these as you read this. Should you need an image in an emergency, please contact us at imagehelp@codebetter.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());

        }

    }


Posted 08-10-2005 7:21 PM by Jeffrey Palermo

[Advertisement]

Comments

Joshua Flanagan wrote re: How to do Url Rewriting with just an HttpHandler (without the side-effects) - level 400
on 08-10-2005 7:14 PM
Interesting. Do you know of a .NET 1.1 (pre-PreRenderComplete) equivalent?

Just curious, why do you implement IRequiresSessionState? Is that just leftover code or is that needed when the target page uses Session?
Don Good wrote re: How to do Url Rewriting with just an HttpHandler (without the side-effects) - level 400
on 08-10-2005 7:28 PM
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?
Jason Haley wrote Interesting Finds
on 08-10-2005 8:56 PM
Christopher Steen wrote Link Listing - August 10, 2005
on 08-10-2005 11:14 PM
"Source Server" - The best "Hidden" feature in Whidbey
Debugging [Via: Matt Pietrek ]
101 Code Samples...
Christopher Steen - Learning .NET wrote Link Listing - August 10, 2005
on 08-10-2005 11:16 PM
"Source Server" - The best "Hidden" feature in Whidbey Debugging [Via: Matt Pietrek ]
101 Code Samples...
Jeffrey Palermo wrote re: How to do Url Rewriting with just an HttpHandler (without the side-effects) - level 400
on 08-11-2005 10:16 AM
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.
Jeffrey Palermo wrote re: How to do Url Rewriting with just an HttpHandler (without the side-effects) - level 400
on 08-11-2005 10:17 AM
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.
Wayne Larimore - his bloggin' Weighs wrote URL Rewriting with HttpHandler - Friendly URL Wonders
on 08-11-2005 3:09 PM
Wayne Larimore - his bloggin' Weighs wrote URL Rewriting with HttpHandler - Friendly URL Wonders
on 08-11-2005 3:09 PM
Link Blog wrote How to do Url Rewriting with just an HttpHandler (without the side-effects) - level 400
on 08-11-2005 5:34 PM
Jeffrey Palermo : How to do Url Rewriting with just an HttpHandler (without the side-effects) - level...
Daniel F wrote re: How to do Url Rewriting with just an HttpHandler (without the side-effects) - level 400
on 08-11-2005 10:30 PM
I like it, I like it a lot. Seems sneaky, but cool nonetheless.
Link Blog wrote How to do Url Rewriting with just an HttpHandler (without the side-effects) - level 400
on 08-18-2005 6:07 PM
Jeffrey Palermo : How to do Url Rewriting with just an HttpHandler (without the side-effects) - level...
Scott Sargent : Codeboy's Blog wrote Just a little bit of Rewriting
on 01-25-2007 1:19 PM

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

snickers wrote re: How to do Url Rewriting with just an HttpHandler (without the side-effects) - level 400
on 02-06-2007 4:37 PM

Wonderful!

kbird wrote re: How to do Url Rewriting with just an HttpHandler (without the side-effects) - level 400
on 06-20-2007 4:22 AM

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

sucharitha wrote re: How to do Url Rewriting with just an HttpHandler (without the side-effects) - level 400
on 09-27-2007 9:34 AM

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?