ASP.NET MVC Framework (Part 2): URL Routing
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:
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.
Default ASP.NET MVC URL Routing Rules
By default when you use Visual Studio to create a new project using the "ASP.NET MVC Web Application" template it adds an ASP.NET Application class to the project. This is implemented within the Global.asax code-behind:
The ASP.NET Application class enables developers to handle application startup/shutdown and global error handling logic.
The default ASP.NET MVC Project Template automatically adds an Application_Start method to the class and registers two URL Routing rules with it:
The first routing rule above indicates that the ASP.NET MVC framework should by default map URLs to Controllers using a "[controller]/[action]/[id]" format when determining which Controller class to instantiate, and which Action method to invoke (along with which parameters should be passed in).
This default routing rule is why a URL request for /Products/Detail/3 in our e-commerce browsing sample from Part 1 automatically invokes the Detail method on our ProductsController class and passes in 3 as the id method argument value:
The second routing rule above is added to special-case the root "Default.aspx" URL in our application (which is sometimes passed by web servers in place of "/" when handling requests for the root URL of an application). This rule ensures that requests for either the root "/Default.aspx" or "/" to our application are handled by the "Index()" action on the "HomeController" class (which is a controller automatically added by Visual Studio when we created a new application using the "ASP.NET MVC Web Application" project template).
Understanding Route Instances
Routing rules are registered by adding Route instances into the System.Web.Mvc.RouteTable's Routes collection.
The Route class defines a number of properties that you can use to configure the mapping rules. You can set these properties using either "traditional" .NET 2.0 property assignments:
Or by taking advantage of the new object initializer feature in the VS 2008 C# and VB compilers to set the properties more tersely:
The "Url" property on the Route class defines the Url matching rule that should be used to evaluate if a route rule applies to a particular incoming request. It also defines how the URL should be tokenized for parameters. Replaceable parameters within the URL are defined using a [ParamName] syntax. As we'll see later, we aren't restricted to a fixed set of "well known" parameter names - you can have any number of arbitrary parameters you want within the URL. For example, I could use a Url rule of "/Blogs/[Username]/Archive/[Year]/[Month]/[Day]/[Title]" to tokenize incoming URLs to blog posts - and have the MVC framework automatically parse and pass UserName, Year, Month, Day and Title parameters to my Controller's action method.
The "Defaults" property on the Route class defines a dictionary of default values to use in the event that the incoming URL doesn't include one of the parameter values specified. For example, in the above URL mapping examples we are defining two default URL parameter values - one for "[action]" and one for "[id]". This means that if a URL for /Products/ is received by the application, the routing system will by default use "Index" as the name of the action on the ProductsController to execute. Likewise, if /Products/List/ was specified, then a null string value would be used for the "ID" parameter.
The "RouteHandler" property on the Route class defines the IRouteHandler instance that should be used to process the request after the URL is tokenized and the appropriate routing rule to use is determined. In the above examples we are indicating that we want to use the System.Web.Mvc.MvcRounteHandler class to process the URLs we have configured. The reason for this extra step is that we want to make sure that the URL routing system can be used for both MVC and non-MVC requests. Having this IRouteHandler interface means we will be able to cleanly use it for non-MVC requests as well (such as standard WebForms, Astoria REST support, etc).
There is also a "Validation" property on the Route class that we'll look at a little later in this post. This property allows us to specify pre-conditions that need to be met for a particular routing rule to match. For example, we could indicate that a routing rule should only apply for a specific HTTP verb (allowing us to easily map REST commands), or we could use a regular expression on arguments to filter whether a routing rule should match.
Note: In the first public MVC preview the Route class isn't extensible (instead it is a data class). For the next preview release we are looking to make it extensible and enable developers to add scenario specific route classes (for example: a RestRoute sub-class) to cleanly add additional semantics and functionality.
Route Rules Evaluation
When an incoming URL is received by an ASP.NET MVC Web Application, the MVC framework evaluates the routing rules in the RouteTable.Routes collection to determine the appropriate Controller to handle the request.
The MVC framework chooses the Controller to use by evaluating the RouteTable rules in the order that they have been registered. The incoming URL is tested against each Route rule to see if it matches - and if a Route rule matches then that rule (and its associated RouteHandler) is the one that is used to process the request (and all subsequent rules are ignored). This means that you want to typically structure your routing Rules in a "most specific to least specific" order.
Routing Scenario: Custom Search URL
Let's walk through using some custom routing rules in a real world scenario. We'll do this by implementing search functionality for our e-commerce site.
We'll start by adding a new SearchController class to our project:
We'll then define two Action methods within our SearchController class. The Index() action method will be used to present a search page that has a TextBox for a user to enter and submit a search term. The Results() action will be used to handle the form submission from it, perform the search against our database, and then display the results back to the user:
Using the default /[controller]/[action]/[id] URL route mapping rule, we could "out of the box" use URLs like below to invoke our SearchController actions:
Scenario | URL | Action Method |
Search Form: | /Search/ | Index |
Search Results: | /Search/Results?query=Beverages | Results |
/Search/Results?query=ASP.NET | Results |
Note that the reason the root /Search URL by default maps to the Index() action method is because the /[controller]/[action]/[id] route definition added by default when Visual Studio creates a new project sets "Index" as the default action on Controllers (via the "Defaults" property):
While URLs like /Search/Results?query=Beverages are perfectly functional, we might decide we want slightly "prettier" URLs for our search results. Specifically we might want to get rid of the "Results" action name from the URL, and pass in the search query as part of the URL instead of using a QueryString argument. For example:
Scenario | URL | Action Method |
Search Form: | /Search/ | Index |
Search Results: | /Search/Beverages | Results |
/Search/ASP.NET | Results |
We could enable these "prettier" search result URLs by adding two custom URL Route mapping rules before the default /[controller]/[action]/[id] rule like below:
With the first two rules we are now explicitly specifying the Controller and Action parameters for /Search/ URLs. We are indicating that "/Search" should always be handled by the "Index" action on the SearchController. Any URL with a sub-URL hierarchy (/Search/Foo, /Search/Bar, etc) is now always handled by the "Results" action on the SearchController.
The second routing rule above indicates that anything beyond the /Search/ prefix should be treated as a parameter called "[query]" that will then be passed as a method parameter to our Results action method on SearchController:
Most likely we will also want to enable paginated search results (where we only show 10 search query results at a time). We could do this via a querystring argument (for example: /Search/Beverages?page=2) or we could optionally embed the page index number as part of the URL as well (for example: /Search/Beverages/2). To support this later option all we'd need to-do is add an extra optional parameter to our 2nd routing rule:
Notice above how the new URL rule match is now "Search/[query]/[page]". We've also configured the default page index to be 1 in cases where it is not included in the URL (this is done via the anonymous type passed as the "Defaults" property value).
We can then update our SearchController.Results action method to take this page parameter as a method argument:
And with that we now have "pretty URL" searching for our site (all that remains is to implement the search algorithm - which I will leave as an exercise to the reader <g>).
Validation Pre-Conditions for Routing Rules
As I mentioned earlier in this post, the Route class has a "Validation" property that allows you to add validation pre-condition rules that must be true (in addition to the URL filter) for a route rule to match. The ASP.NET MVC Framework allows you to use regular expressions to validate each parameter argument in the URL, as well as allows you to evaluate HTTP headers (to route URLs differently based on HTTP verbs).
Below is a custom validation rule we could enable for URLs like "/Products/Detail/43". It specifies that the ID argument must be a number (no strings allowed), and that it must be between 1 and 8 characters long:
If we pass in a URL like /Products/Detail/12 to our application, the above routing rule will be valid. If we pass in /Products/Detail/abc or /Products/Detail/23232323232 it will not match.
Constructing Outgoing URLs from the Routing System
Earlier in this blog post I said that the URL routing system in the ASP.NET MVC Framework was responsible for two things:
- Mapping incoming URLs to Controllers/Actions to handle
- Helping construct outgoing URLs that can be used to later call back to Controllers/Actions (for example: form posts, <a href=""> links, and AJAX calls)
The URL routing system has a number of helper methods and classes that make it easy to dynamically look up and construct URLs at runtime (you can also lookup URLs by working with the RouteTable's Route's collection directly).
Html.ActionLink
In Part 1 of this blog series I briefly discussed the Html.ActionLink() view helper method. It can be used within views and allows you to dynamically generate <a href=""> hyperlinks. What is cool is that it generates these URLs using the URL mapping rules defined in the MVC Routing System. For example, the two Html.ActionLink calls below:
automatically pick up the special Search results route rule we configured earlier in this post, and the "href" attribute they generate automatically reflect this:
In particular note above how the second call to Html.ActionLink automatically mapped the "page" parameter as part of the URL (and note how the first call omitted the page parameter value - since it knew a default value would be provided on the server side).
Url.Action
In addition to using Html.ActionLink, ASP.NET MVC also has a Url.Action() view helper method. This generates raw string URLs - which you can then use however you want. For example, the code snippet below:
would use the URL routing system to return the below raw URL (not wrapped in a <a href=""> element):
Controller.RedirectToAction
ASP.NET MVC also supports a Controller.RedirectToAction() helper method that you can use within controllers to perform redirects (where the URLs are computed using the URL routing system).
For example when the below code is invoked within a controller:
It internally generates a call to Response.Redirect("/Search/Beverages")
DRY
The beauty of all of the above helper methods is that they enable us to avoid having to hard-code in URL paths within our Controller and View Logic. If at a later point we decide to change the search URL route mapping rule back from "/Search/[query]/[page]" to "/Search/Results/[query]/[page]" or /Search/Results?query=[query]&page=[page]" we can easily do so by editing it in one place (our route registration code). We don't need to change any code within our views or controllers to pick up the new URL (this maintaining the "DRY principle").
Constructing Outgoing URLs from the Routing System (using Lambda Expressions)
The previous URL helper examples took advantage of the new anonymous type support that VB and C# now support with VS 2008. In the examples above we are using anonymous types to effectively pass a sequence of name/value pairs to use to help map the URLs (you can think of this as a cleaner way to generate dictionaries).
In addition to passing parameters in a dynamic way using anonymous types, the ASP.NET MVC framework also supports the ability to create action routes using a strongly-typed mechanism that provides compile-time checking and intellisense for the URL helpers. It does this using Generic types and the new VB and C# support for Lambda Expressions.
For example, the below anonymous type ActionLink call:
Can also be written as:
In addition to being slightly terser to write, this second option has the benefit of being type-safe, which means that you get compile-time checking of the expression as well as Visual Studio code intellisense (you can also use refactoring tools with it):
Notice above how we can use intellisense to pick the Action method on the SearchController we want to use - and how the parameters are strongly-typed. The generated URLs are all driven off of the ASP.NET MVC URL Routing system.
You might be wondering - how the heck does this work? If you remember eight months ago when I blogged about Lambda Expressions, I talked about how Lambda expressions could be compiled both as a code delegate, as well as to an expression tree object which can be used at runtime to analyze the Lambda expression. With the Html.ActionLink<T> helper method we using this expression tree option and are analyzing the lambda at runtime to look up the action method it invokes as well as the parameters types, names and values that are being specified in the expression. We can use these with the MVC Url Routing system to return the appropriate URL and associated HTML.
Important: When using this Lambda Expression approach we never actually execute the Controller action. For example, the below code does not invoke the "Results" action method on our SearchController:
Instead it just returns this HTML hyperlink:
When this hyperlink is clicked by an end-user it will then send back a http request to the server that will invoke the SearchController's Results action method.
Unit Testing Routes
One of the core design principles of the ASP.NET MVC Framework is enabling great testing support. Like the rest of the MVC framework, you can easily unit test routes and route matching rules. The MVC Routing system can be instantiated and run independent of ASP.NET - which means you can load and unit test route patterns within any unit test library (no need to start up a web-server) and using any unit test framework (NUnit, MBUnit, MSTest, etc).
Although you can unit test an ASP.NET MVC Application's global RouteTable mapping collection directly within your unit tests, in general it is usually a bad idea to have unit tests ever change or rely on global state. A better pattern that you can use is to structure your route registration logic into a RegisterRoutes() helper method like below that works against a RouteCollection that is passed in as an argument (note: we will probably make this the default VS template pattern with the next preview update):
You can then write unit tests that create their own RouteCollection instance and call the Application's RegisterRoutes() helper to register the application's route rules within it. You can then simulate requests to the application and verify that the correct controller and actions are registered for them - without having to worry about any side-effects:
Summary
Hopefully this post provides some more details about how the ASP.NET MVC Routing architecture works, and how you can use it to customize the structure and layout of the URLs you publish within your ASP.NET MVC applications.
By default when you create a new ASP.NET MVC Web Application it will pre-define a default /[controller]/[action]/[id] routing rule that you can use (without having to manually configure or enable anything yourself). This should enable you to build many applications without ever having to register your own custom routing rules. But hopefully the above post has demonstrated that if you do want to custom structure your own URL formats it isn't hard to-do - and that the MVC framework provides a lot of power and flexibility in doing this.
Hope this helps,
Scott