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());


        }


    }