[link] Rewriting the URL using IHttpHandlerFactory

Don Good told me about Jeff Putz's cool article on Rewriting the URL using IHttpHandlerFactory. I don't know how I missed that one. It's a great technique that gets around all the grimy hacks you need if you're doing this the standard way, using HttpContext.Current.RewritePath(someFile). This one instead maps a custom handler for ASPX files to your class which implements IHttpHandlerFactory. Then in the code logic, you just load the code from the physical ASPX file instead of redirecting to it and screwing with your context:

using System;
using System.IO;
using System.Web;
using System.Web.UI;

public class MyPageFactory : IHttpHandlerFactory
{
   
public IHttpHandler GetHandler(HttpContext context, string requestType, 
      
string url, string pathTranslated)
   {
      context.Items["fileName"] = Path.GetFileNameWithoutExtension(url).ToLower();
      
return PageParser.GetCompiledPageInstance(url, 
         context.Server.MapPath("~/Content.aspx"), context);
   }

   
public void ReleaseHandler(IHttpHandler handler)
   {
   }
}

Read the article - it's short and well written. Don showed me a prototype that was using this, and it worked perfectly. Great idea!

1 Comment

Comments have been disabled for this content.