By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
425,763 Members | 1,609 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 425,763 IT Pros & Developers. It's quick & easy.

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

P: n/a
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.Curren t.Request.Path,

HttpContext.Current.Items["originalPathInfo"].ToString(),

HttpContext.Current.Items["originalQuerystring"].ToString());

}

}

10 Comments

Nov 19 '05 #1
Share this question for a faster answer!
Share on Google+

This discussion thread is closed

Replies have been disabled for this discussion.