URL Re-Writing The Right Way! (It's Easy)
(
Sep 14 2007 - 12:05:14 AM by
Timothy Khouri) - [
print blog
post]
Recently (actually about 4 hours ago) I wrote a blog post about how to fake URL re-writing in ASP.NET. In fact, I even used that method on Eels for a long time as a very lazy work around until I decided how I wanted the structure of things to work. So, after writing that post, I realized the time had come and gone for allowing sloppy code, and that now I had to fix it.
So, I wanted to recap what I did in order to map your own HTTP requests, and how I've now fixed my bad ways (and how easy it was to do so). So, first of all, what I was doing before was tapping into the "Application_Error" method in the Global.asax file. If an exception was thrown in my web app, and there was no "Handler" assigned (which happens in a 404 scenario), I would then check the URL and if it was an attempt to read an article, I would redirect them to the right page myself.
void Application_Error(object sender, EventArgs e)
{
if (this.Context.Handler == null)
{
string physicalPath = this .Request.PhysicalPath.ToLower();
if (physicalPath.StartsWith(global_asax .articlesDirectoryPath))
{
this.Context.Handler = PageParser .GetCompiledPageInstance("~/Articles/Default.aspx",
Server.MapPath("~/Articles/Default.aspx"), HttpContext.Current);
this.Server.ClearError();
}
}
}
This was a very poor design and was supposed to only be a work around until I decided how I wanted the structure of Eels to be. Well, months have passed and now I've fixed the above to do what I should have done in the first place - make my own HttpHandlers. So here is what I added to my web.config:
<httpHandlers>
<add verb="*"
path="Articles/*.aspx"
type="EelsArticleHandler" />
</httpHandlers>
And here is my HttpHandler class (which I have in my App_Code directory of course):
using System;
using System.Web;
using System.Web.UI;
public class EelsArticleHandler : IHttpHandler
{
public bool IsReusable
{
get
{
return false;
}
}
public void ProcessRequest(HttpContext context)
{
context.Handler = PageParser.GetCompiledPageInstance("~/Articles/Default.aspx", context.Server.MapPath("~/Articles/Default.aspx"), context);
context.Handler.ProcessRequest(context);
}
}
I guess doing things the right way isn't that hard now is it :)