Republished with Permission - Original Article
Last month I blogged the first in a series of posts I'm going to write
that cover the new ASP.NET MVC Framework we are working on. The first post in this series built a simple e-commerce product
listing/browsing scenario. It covered the high-level concepts behind MVC,
and demonstrated how to create a new ASP.NET MVC project from scratch to
implement and test this e-commerce product listing functionality.
In today's blog post I'm going to drill deeper into the
routing architecture of the ASP.NET MVC Framework, and discuss some of the cool
ways you can use it for more advanced scenarios in your application.
Quick Recap from Part 1
In Part 1 of this series, we created an e-commerce site that
exposed three types of URLs:
URL Format
|
Behavior
|
URL Example
|
/Products/Categories
|
Browse all Product Categories
|
/Products/Categories
|
/Products/List/Category
|
List Products within a Category
|
/Products/List/Beverages
|
/Products/Detail/ProductID
|
Show Details about a Specific Product
|
/Products/Detail/34
|
We handled these URLs by creating a
"ProductsController" class like below:
Figure 1
Once the above class was added to our application, the
ASP.NET MVC Framework automatically handled routing the incoming URLs to the
appropriate action method on our controller to process.
In today's blog post we are going to drill into exactly how
this URL mapping happened, as well as explore more advanced routing scenarios
we can take advantage of with the ASP.NET MVC Framework. I'll also demonstrate
how you can easily unit test URL routing scenarios.
What does the ASP.NET MVC URL Routing System do?
The ASP.NET MVC framework includes a flexible URL routing
system that enables you to define URL mapping rules within your
applications. The routing system has two main purposes:
Map incoming URLs to the application and route them so that
the right Controller and Action method executes to process them
Construct outgoing URLs that can be used to call back to
Controllers/Actions (for example: form posts, <a href="">
links, and AJAX calls)
Having the ability to use URL mapping rules to handle both
incoming and outgoing URL scenarios adds a lot of flexibility to application
code. It means that if we want to later change the URL structure of our
application (for example: rename /Products to /Catalog), we could do so by
modifying one set of mapping rules at the application level - and not require
changing any code within our Controllers or View templates.