THE ROUTING SYSTEM ASSEMBLY

Một phần của tài liệu Giáo trình lập trình ASP.NET Apress pro ASP NET MVC3 framework pre release (Trang 296 - 302)

Although the routing system was needed by the ASP.NET MVC framework, it was intended to be used with other ASP.NET technologies as well, including Web Forms. Because of this, the routing system classes are in the System.Web assembly and not in System.Web.Mvc.

When you create a new MVC application, you will see that Visual Studio has added a reference to the System.Web.Routing assembly – this is a holdover from support for .NET 3.5 and has no effect on your project. You can delete this assembly without any problemsreference if you wish.

We focus on using routing with the MVC framework, but much of the information applies when using routing with other parts of the ASP.NET platform. Adam has included a lot of information about using routing with the base ASP.NET platforms and with Web Forms in his book Applied ASP.NET 4 in Context.

Introducing the Routing System

The routing system has two functions. The first is to examine an incoming URL and figure out which controller and action the request is intended for – as you might expect, this is what we want the routing system to do when we receive a client request. The second function is to generate outgoing URLs – these are the URLs that appear in the HTML rendered from our views so that a specific action will be invoked when the user clicks on the link (at which point it because has become an incoming URL again, of course).

In the first part of this chapter, we will focus on defining routes and using them to process incoming URLs so that the user can navigate toreach your controllers and actions. Once we have done that, we’ll show you how to use those same routes to generate the outgoing URLs you will need to include in your HTML.

Creating the Routing Project

To demonstrate the routing system, we need a project to which we can add routes. We have created a new MVC application using the Internet Application template – we called the project UrlsAndRoutes. We selected this template because it gives us some ready-made controllers and actions to work with.

Routes are defined in Global.asax. If you open this file in Visual Studio, you will see that routes take up quite a lot of this (admittedly short) file. Listing 11-1 contains the

Global.asax from our project, which we have edited slightly to make it more readable.

Note Strictly speaking, routes are defined in Global.asax.cs, which is the code-behind file for Global.asax. When you double-click on Global.asax in the Solution Explorer window, it is Global.asax.cs that Visual Studio actually opens. For that reason, we are going to refer to both files collectively as Global.asax.

Listing 11-1. The default Global.asax.cs file using System.Web.Mvc;

using System.Web.Routing;

namespace UrlsAndRoutes {

public class MvcApplication : System.Web.HttpApplication { protected void Application_Start() {

AreaRegistration.RegisterAllAreas();

RegisterGlobalFilters(GlobalFilters.Filters);

RegisterRoutes(RouteTable.Routes);

}

public static void RegisterRoutes(RouteCollection routes) { ... routes are defined here...

}

public static void RegisterGlobalFilters(GlobalFilterCollection filters) { filters.Add(new HandleErrorAttribute());

} } }

The Application_Start method is called by the underlying ASP.NET platform when the application is first started, which leads to the RegisterRoutes method being called. The

parameter to this method is the value of the static RouteTable.Routes property, which is an instance of the RouteCollection class – we’ll come back to this class later.

We have deleted the routes that are added by default from the RegisterRoutes method because we want to show you the different techniques for creating routes and the different kinds of route that are available. Before we can do that though, we need to take a step back and look at the something which is central to the routing system.

Introducing URL Patterns

The routing system works its magic using a set of routes – these routes collectively comprise the URL schema or scheme for an application, which is the set of URLs that your application will recognize and respond to.

We don’t have to manually type out all of the individual URLs we are willing to support – instead, each route contains a URL pattern, which is compared to an incoming URL.

If the pattern matches the URL, then it is used by the routing system to process that URL. Let’s start with an example URL from the SportsStore application:

http://mysite.com/Admin/Index

This is the URL that we used to access the administrator’s view of the product

catalogue. If you refer back to Chapter 9, you will see that this URL referred to the Index action method in the AdminController class.

URLs can be broken down into segments – these are the parts of the URL, excluding the hostname and query string, that are separated by the / character. In the URL above, there are two segments, as shown in Figure 11-1.

Figure 11-1. The segments in an example URL

The first segment contains the work Admin and the second segment contains the word Index. To the human eye, it is obvious that the first segment relates to the controller and the second segment relates to the action – but, of course, we need to express this relationship in a way that the routing system can understand. Here is a URL pattern that does this:

{controller}/{action}

When processing an incoming URL, the job of the routing system is to match the URL to a pattern and then extract values from the URL for the segment variables defined in the pattern. The segment variables are expressed using braces (the { and } characters) – in the pattern above, there are two segment variables with the names controller and action. We say match to a pattern, because an MVC application will usually have several routes and the routing system will compare the incoming URL to the URL pattern of each route until it can find a match.

Tip The routing system doesn’t have any special knowledge of controllers and actions – it just extracts values for the segment variables and passes them along the request pipeline. It is later in the pipeline, when the request reaches the MVC framework proper, that meaning is assigned to the

controller and action variables. This is why the routing system can be used with Web Forms and, as we shall see, how we are able to create our own variables.

By default, a URL pattern will match any URL that has the right number of segments – for example, the pattern above will match any URL that has two segments, as illustrated by Table 11-2.

Table 11-2. Matching URLs

Request URL Segment Variables

http://mysite.com/Admin/Index controller = Admin action = Index http://mysite.com/Index/Admin controller = Index

action = Admin http://mysite.com/Apples/Oranges controller = Apples

action = Oranges

http://mysite.com/Admin No match – too few segments

http://mysite.com/Admin/Index/Soccer No match – too many segments

Table 11-2 highlights two key behaviors of URL patterns. The first aspect is that URL patterns are conservative – they will only match URLs that have the same number of segments as the pattern. You can see this in the fourth and fifth examples in the table. The second aspect is that URL patterns are also liberal – if a URL does have the right number of segments, the pattern will extract the value for the segment variable, whatever it might be.

Tip These are the default behaviors, and we’ll show you how to vary them later in the chapter, but these are the keys to understanding how URL patterns function.

As we mentioned, the routing system doesn’t know anything about an MVC application, and so URL patterns will match even when there is no controller or action that corresponds to the values extracted from a URL. You can see this demonstrated in the second example in the table – we have transposed the Admin and Index segments in the URL, and so the values extracted from the URL have also been transposed.

Creating and Registering a Simple Route

Once we have a URL pattern in mind, we can use it to define a route. Listing 11-2 shows how we can create a route using the example URL pattern from the previous section in the

RegisterRoutes method of Global.asax.

Listing 11-2. Registering a Route

public static void RegisterRoutes(RouteCollection routes) {

Route myRoute = new Route("{controller}/{action}", new MvcRouteHandler());

routes.Add("MyRoute", myRoute);

}

We create a new route object, passing in our URL pattern as a constructor parameter.

We also pass in an instance of MvcRouteHandler – different ASP.NET technologies provide different classes to tailor the routing behavior, and this is the class we use for ASP.NET MVC applications. Once we have created the route, we add it to the RouteCollection object using the Add method, passing in the name we want the route to be known by and the route we have created.

Tip Naming your routes is optional, and there is an argument that doing so contravenes the principles behind the MVC design patternsacrifices some of the clean separation of concerns that otherwise comes from routing. We are pretty relaxed about naming, but we explain why this can be a problem in the Generating a URL from a Specific Route section, later in this chapter.

A more convenient way of registering routes is to use the MapRoute method defined in the RouteCollection class. Listing 11-3 shows how we can use this method to register our route.

Listing 11-3. Registering a route using the MapRoute method public static void RegisterRoutes(RouteCollection routes) { routes.MapRoute("MyRoute", "{controller}/{action}");

}

This approach is slightly more compact – not least because we don’t have to create an instance of the MvcRouteHandler class. The MapRoute method is solely for use with MCV MVC application –ASP.NET Web Forms applications can use the MapPageRoute method, also defined in the RouteColleciton class.

Một phần của tài liệu Giáo trình lập trình ASP.NET Apress pro ASP NET MVC3 framework pre release (Trang 296 - 302)

Tải bản đầy đủ (PDF)

(603 trang)