Url Rewriting with just an HttpHandler (without the side-effects)

A

Anonieko

Jefrey Palermo

How to do Url Rewriting with just an HttpHandler (without the
side-effects) - level 400
posted on Wednesday, August 10, 2005 7:21 PM
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());

}

}

10 Comments
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,755
Messages
2,569,537
Members
45,021
Latest member
AkilahJaim

Latest Threads

Top