12.11.08

URL rewriting in Global.asax

I needed an easy way to redirect or rewrite a request in my APS.NET web application. The purpose is off course to get rid of the many aspx files and to be able to serve frindly URL's. I was searching for an approach like rewriting URL's in .htaccess on the Apache web server.

I found different solutions – a lot of them a little complicated.

As descried in URL Rewriting with ASP.NET on CodeProject .NET has a method for rewriting a incoming requests:

void HttpContext.RewritePath(string path)

A good start (actually I should use this method more often), but not enough. I needed a way to catch incoming requests before entering OnInit and Page_Load – Global.asax was the answer.

As a start I rewrite all incoming requests:

<%@ Application Language="C#" >
<script runat="server">
void Application_BeginRequest(object sender, EventArgs e)
{
HttpContext.Current.RewritePath("/default.aspx");
}
</script>

This works as suspected – all requests are rewritten to /default.aspx. But what about images, javaScript files ex.? If a file exist I let the request pass:

<%@ Application Language="C#" >
<%@ Import Namespace="System.IO" %>
<script runat="server">
void Application_BeginRequest(object sender, EventArgs e)
{
if (!File.Exists(HttpContext.Current.Request.PhysicalPath))
{
HttpContext.Current.RewritePath("/default.aspx");
}
}
</script>

The last thing is to decide what to do with the request. In default.aspx I get the original path with the property:

HttpRequest.RawUrl

Of course you can evaluate the URL in many different ways depending on what you need. This presentation is somewhat simplified, but I hope you see the point.

Post a Comment