Easy URL Rewriting With ASP.NET Routing

URL rewriting is a great way to avoid the problems typically associated with the standard .NET way of building web apps.  Take this typical URL, for example:

http://www.site.com/displaycategory.aspx?category=tools

Most ASP.NET solutions wind up having URLS that look like this.  It works, but there are problems with these types of URLs:

  • They’re long and ugly.
  • They make things look complicated and scary to typical end users.
  • They don’t let power users understand and navigate the site through modifying the URL.
  • Search engines don’t like them
  • Inner workings of your code are exposed, which could lead to security issues.
  • URLs are tied to the specific implementation

What you really want is to have that same web page handling requests, but accessed through an URL like this:

http://www.site.com/categories/tools

There are two great tools in the ASP.NET world to rewrite URLS: The IIS URL Rewrite module, and the System.Web.Routing functionality built into the framework.  Unfortunately, they both have serious drawbacks.

The URL Rewrite module snaps into IIS and lets you configure rewriting without touching any code.  It’s worth researching this tool a bit, because depending on what you’re trying to accomplish, it might suit your needs exactly.  But, it does suffer some serious drawbacks for .NET developers:

  • The URL Rewrite module must be installed on the server.
  • Visual Studio is not aware of URL Rewrite.
  • URL Rewrite doesn’t work with the ASP.NET Development Server built into Visual Studio; you have to build and debug your application through IIS.
  • You can only configure rewrites through the limited URL Rewrite scheme; you can’t write code.

ASP.NET Routing doesn’t suffer from these drawbacks, but while it’s far more powerful, it’s also far more complicated to set up.  It does require code changes, and when used in the traditional manner, it requires each page in your site to be rewritten to use the Routing architecture.  This means a lot of work.  But, there’s a very easy way to harness the power of Routing and use it much like you would the URL Rewrite module.

Enable routing for your application

The first thing you’ll need to do is map a page route within your application.  This is done through code.  The Global.asax class contains a method called Application_Start which is run whenever your application starts, so it’s an ideal place for this.  Find this method, and add this code:

// Register routing
System.Web.Routing.RouteCollection routes = System.Web.Routing.RouteTable.Routes;
routes.Ignore("{resource}.axd/{*pathInfo}");
routes.MapPageRoute("Generic Routing", "{page}/{*id}", "~/routing.aspx");

There are three important arguments to the MapPageRoute call: a friendly name for the route you’re adding (call it whatever you’d like), the format of the URL that’s going to be caught, and the path to the ASP.NET page you’d like to handle matching URLs.  In this example, we’re going to catch URLs of the style used as an example at the top of this page, but you could easily change this to work with an MVC pattern or anything else you need.  Of course, you’re not limited to just one mapping, but that’s all we need for this example.  The asterisk is used to indicate that the {id} part of the URL pattern could contain slashes. The call to .Ignore prevents requests to WebResource.axd from being caught by your routing.

Build your routing pages

Now, add a page called “routing.aspx” to your project, and add this code to Page_Load:

// Get routing data
string page = (string)this.RouteData.Values["page"];
string id = (string)this.RouteData.Values["id"];

// Transfer to appropriate page
if (page == "categories")
Server.Transfer(string.Format("~/displaycategory.aspx?category={0}", id));
else if (page == "titles")
Server.Transfer(string.Format("~/displaytitle.aspx?title={0}", id));

You can see what’s going on here: the code gathers the values that were used to built the URL, checks to see which page should handle the request, and then forwards the request on the the proper page.  In this example, we also remap requests to URLs like this:

http://www.site.com/titles/ExampleTitle

From this point forward, you can configure as many rewrites as you’d like through this one little bit of code.  Because this is code, though, you can modify this to suit whatever needs you may have.  If you wanted, you could even write this to draw data from an XML file so you don’t need to touch code to edit your URL mappings.

Really, this is the best of both worlds: easy to configure, drop-in URL rewriting that will work with any existing solution that doesn’t require anything to be installed, works with Visual Studio, and lets you write code wherever you need a bit more complexity.

12 comments:

  1. can i get sample project. Mail id is rajath@xpditesolutions.com

    ReplyDelete
  2. Absolutely; I would be more than happy to help your company. Will our standard consulting rate of C$185/hour (plus disbursements) be acceptable?

    ReplyDelete
  3. After slicing your hemp twine provide the hemp thread and lower 10 items only one foot long.

    ReplyDelete
  4. After slicing your hemp twine provide the hemp thread and lower 10 items only one foot long.

    ReplyDelete
  5. After slicing your hemp twine provide the hemp thread and lower 10 items only one foot long.

    ReplyDelete
  6. After slicing your hemp twine provide the hemp thread and lower 10 items only one foot long.

    ReplyDelete
  7. After slicing your hemp twine provide the hemp thread and lower 10 items only one foot long.

    ReplyDelete
  8. I have a hard time in analyzing urls.. Well, It’s a helpful blog indeed! Especially in understanding seo url rewriting .

    ReplyDelete
  9. Hà Nội Đủ được đứng cùng hàng ngũ với 10 tổ chức phi chính phủ dành cho thanh niên mà bạn nên tham gia nà
    dịch vụ kế toán thuế quận phú nhuận
    dịch vụ kế toán thuế tại biên hòa đồng nai
    dịch vụ dọn dẹp sổ sách tại tp hcm
    Không có gì có thể thay thế, trong con mắt của sự phi lý
    Không có gì có thể nhớ, thế giới của sự tồn tại của tôi

    ReplyDelete

  10. This blog is very interesting.I am long time user of this tool. Using it you can check and re write URLs of your website.

    ReplyDelete
  11. باعتباري شخصًا يعيش بمفرده ، غالبًا ما نقلت قطعًا ثقيلة من الأثاث لوحدي مع القليل من البراعة والحيل. ومع ذلك ، فقد علمت أيضًا أن تولي الكثير من جانبي بنفسي يمكن أن يؤدي إلى إصابات أو مواقف محرجة.
    شركة نقل عفش
    شركة نقل عفش من الرياض الى الدمام
    شركة نقل اثاث من الرياض الى الدمام
    شركة نقل عفش بحائل

    ReplyDelete


Copyright © 2010 Paul Guenette and Matthew Sleno.