Understanding Routing Precedence in ASP.NET MVC and Web API

Routing can be a very tricky issue within ASP.NET MVC and Web API applications. This can be especially true if you have a variety of different routes with varying parameters defined in such a way that a single request could satisfy multiple routes.

This blog post will cover some of the precedence rules that are applied to routing in ASP.NET MVC and Web API and how to leverage these to ensure that the route you want to use gets used.

What are Routes? How Do They Work?

A Route in ASP.NET simply consists of a pattern and this pattern is going to be mapped to a handler. The handlers themselves can be a variety of different mechanisms (e.g. a physical file, a Web Forms page, or an MVC Controller class). In simplest terms, Routes define how requests are handled within your application.

Routes will consist of the following three components:

A name to identify the Route itself.

A pattern to match URLs to match a request with its appropriate handler.

A handler to tell requests that match the pattern where to go.

You can see an example of a route declaration in ASP.NET MVC below, which contains all three of these criteria:

Since the focus of this post isn't really about routing itself and more of routing precedence, I won't go into any more detail about declaring them.

ASP.NET will store all of the defined routes within a Routes Table and when a request comes, it will look through these routes to determine the one best suited to serve for the request. To know how this works, we need to know how routes are prioritized and that's why this blog post exists at all.

tl;dr; Routes match requests using a pattern and tell them where to go.

Routing Precedence

Routing can be a blessing and a curse within an application. It can provide you with the freedom to define all sorts of very creative and easily understandable approaches to accessing data, but when overused, things can get hairy. The primary reason that routing can make you want to pull your hair out is that a single request can match multiple routes.

Routing order can be broken down into the following steps:

Check the Order property (if available).

Order all routes without an explicit Order attribute as follows:

Literal segments

Route parameters with constraints

Route parameters without constraints

Wildcard parameter segments with constraints

Wildcard parameter segments without constraints

As a tie-breaker, order the routes via a case-insensitive string comparison.

Confused yet? That's okay.

Let's talk about defining Route Order and the different types of routes for a moment to clear things up.

Route Order

You can use the [Route] attribute to explicitly set when a particular route is going to be checked against via the Order property. By default, all defined routes have an Order value of 0 and routes are processed from lowest to highest. This is the primary reason that it is so important for establishing route precedence, as it's a single attribute that will govern the order that routes are processed.

Since the Alpha route has an Order property of 1, it will always be evaluated last out of these three routes. The only scenarios where that would not be true would be if another route had a higher Order value or an equal one (and it received priority via the other criteria).

Literal Segments

A Literal Segment route can be thought of as a "hard-coded" route. It contains no types of parameters and no constraints. A few examples of these types of routes might look like:

/widgets/broken
/employees

Route Parameters

Route parameters are going to have a bit more information that literals, but not by much. The only major difference is that they will have a "placeholder" that can be used to define parameters (similar to the String.Format() method).

/widgets/{widgetId}
/reports/{year}/{month}

Route Parameters with Constraints

Route parameters can also be constrained to a specific type. This is important as they will be evaluated prior to unconstrained ones:

/widgets/{widgetId:int}
/reports/{year:int}/{month:int}

Wildcard Parameters

Wildcard parameters are the last type of parameters to review and you generally won't see these as much as the aforementioned types. These function as "catch-all" parameters and may contain more than a single segment.

Consider the following route :

/query/widgets/{*queryvalues}

Notice the {*queryvalues} segment, the leading asterisk indicates that this is a wildcard parameter and thus it can accept all sorts of additional segments in it:

/query/widgets/broken
/query/widgets/byyear/2015

Wildcard Parameters with Constraints

Wildcard parameters can also feature type constraints just like normal route parameters as well if you are expecting a certain type:

/query/widgets/{*byyear:int}

Applying Precedence in Action

Now to break this down, let's define several actions that meet the criteria at least one of each of these routes and we will look at each phase as we order the routes:

Firstly, check the routes for the Order attribute. Now since the GetBroken() action has an Order of 1, we know that this will be the last route to be evaluated (since the default is 0 and routes are processed in ascending order):

After literals, the next routes to be processed are constrained route parameters. The Get(int) action meets this requirement as it accepts an integer for its widgetId parameter, so it will fall next in line:

After all of the literals and route parameters have been routed, the next to be evaluated are the wildcard parameters. More specifically, the constrained wildcard parameters, which the GetbyManufacturedDate(DateTime) route matches:

And finally, the last route type to evaluate is unconstrained wildcard parameters (or "catch-all" routes). The GetByFeatures(string) route fits under that category so it will be placed prior to the GetBroken() route, which had a higher Order property:

And that's it as we don't have any ties to break, but if a tie between two routes did exist, then a case-insensitive comparison of the route template names would resolve it.

Any requests that come through will be evaluated in that order (i.e. the first pattern to match against the URL will be action that handles the request).

Your Mileage May Vary

One important thing to point out in a post like this is that generally you shouldn't have to deal with routing precedence too often. If you are responsible for building and designing your API, then try to keep your API as simple as possible.

Don't try to create this sprawling, verbose API of endless routes unless you absolutely have to. Complicated APIs can lead to complicated problems and in most cases if your API is too difficult to interact with, others won't likely want to use it (especially if you are building a public-facing API).

License

Share

About the Author

An experienced Software Developer and Graphic Designer with an extensive knowledge of object-oriented programming, software architecture, design methodologies and database design principles. Specializing in Microsoft Technologies and focused on leveraging a strong technical background and a creative skill-set to create meaningful and successful applications.

Well versed in all aspects of the software development life-cycle and passionate about embracing emerging development technologies and standards, building intuitive interfaces and providing clean, maintainable solutions for even the most complex of problems.