Asked by
Salman Haide
in
Computers & Technology
at
12:22 PM on November 07, 2008
raj u's Answer
hi haide !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.ToStrin g();
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.GetCompiledPageIns tance(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(Htt pContext.Current.Request.Path,
HttpContext.Current.Items["original PathInfo"].ToString(),
HttpContext.Current.Items["original Querystring"].ToString());
}
}
Answered at
1:11 PM on November 07, 2008
Read all answers