ASP. NET MVC2 chapter I

Source: Internet
Author: User
§ 8 URLs and Routing

Before ASP. net MVC, the core assumption of routing in ASP. net (just like in your other web application platforms) was that URLs correspond directly to files on the server's hard disk. the server executes and serves the page or file corresponding to the incoming URL. table 8-1 gives an example

In this way, there are many restrictions. Some people do not want to let others know the path of their files, or these expressions are too embarrassing.

 

§ 8. 1 putting the programmer back in control

ASP. net MVC breaks this situation, since ASP. net MVC's requests are handled by Controller classes (compiled into. net assembly), there are no special files corresponding to incoming URLs. therefore, there is no specific file corresponding to the path.

You are given complete control of your URL schema-that is, the set of URLs that are accepted and Their mappings to controllers and actions. Let's take a look at how to define the path in MVC.

This is all managed by the Framework's routing system. This is completely managed by the Framework's path system.

 

§ 8. 1.1 about routing and Its. Net assemblies

The routing system was originally designed for ASP. net MVC, but it was always intended to be shared with other ASP. NET technologies, including web forms. the path system is intended for MVC, but it will also be used by other Asp.net technologies. so the pathCodeIs placed in an independentProgramSet (system. Web. Routing. dll in. Net 3.5, and simply system. Web. dll in. Net 4), instead of in system. Web. MVC. dll.

 

§ 8. 2 setting up routes

Let's take a look at the path configuration in the global. asax. CS file.

 public class mvcapplication: system. web. httpapplication {public static void registerroutes (routecollection routes) {routes. ignoreroute ("{resource }. axd/{* pathinfo} "); routes. maproute ("default", // route name "{controller}/{action}/{ID}", // URL with parameters new {controller = "home ", action = "Index", id = urlparameter. optional} // parameter default value);} protected void application_start () {arearegistration. registerallareas (); registerroutes (routetable. routes) ;}}

when the application first starts up (I. E ., when application_start () runs), The registerroutes () method populates a Global static routecollection object called routetable. routes. that's where the application's routing configuration lives. the most important code is that shown in bold: maproute () adds an entry to the routing configuration. to understand what it does a little more clearly, you shoshould know that this call to maproute () is just a concise alternative to writing the following: when the application starts, that is, when application_start () is used, the static registerroutes () method loads a file called routetable. the Global static routecollection object of routes. it is also the place where the placement path is configured. maproute is the path configuration entry. For a simple description, let's take the following example.

Route myroute = new route ("{controller}/{action}/{ID}", new mvcroutehandler () {defaults = new routevaluedictionary (New {controller = "home ", action = "Index", id = urlparameter. optional})}; routes. add ("default", myroute );

The code we see above is synonymous with the code automatically generated by the system.

 

§ 8. 2.1 understanding the routing mechanic

The routing mechanic runs early in the framework's request processing pipeline. its job is to take an incoming URL and use it to obtain an ihttphandler object that will handle the request. the early-rising Routing Mechanism runs in the request processing pipeline of the framework. its job is to use the included URL and use it to obtain a requestIhttphandlerObject

Using newcomers to the MVC Framework struggle with routing. it isn' t comparable to anything in earlier ASP. NET technologies, and it's easy to configure wrong. by understanding its inner workings, you'll avoid these difficulties, and you'll also be able to extend the mechanic powerfully to add extra behaviors using SS your whole application. many newcomers to the MVC Framework are confused about the concept of routing. because it is different from any other Asp.net technology in the past, and it is easy to configure errors. by understanding its internal operations, we can avoid these problems. You can also increase the overall application expansion by adding additional actions.

The main characters: routebase, route, and routecollection

The route configuration consists of three parts:

    • RoutebaseIs the abstract base class for a routing entry. you can implement unusual routing behaviors by deriving a custom type from it (I 've been ded an example near the end of this chapter), but for now you can forget about it.
    • RouteIs the standard, commonly used subclass of routebase that brings in the notions of URL templating, defaults, and constraints. This is what you'll see in most examples.
    • ARoutecollectionIs a complete routing configuration. It's an ordered list of routebase-derived objects (e.g., route objects ).
How routing fits into the request processing pipeline

When a URL is requested, the system invokes each of the ihttpmodules registered for the application. When a URL is requested, the system calls each registeredIhttpmodules. One of them isUrlroutingmodule

 

The order of your route entries is important

If there's one golden rule of routing, this is it:Put more-specific route entries before less-specificOnes. If there is a golden rule for routing configuration: Put the special path before the general path, because the systemAlgorithmStarting from the top, rather than finding the most suitable one.

 

§ 8. 2.2 adding a route entry

The default route is very common. If you want to process other types of URLs, you still need to do some work. let me give you a simple example. For example, we want to use URL/catalog to view all the products in this series.

Routes. Add (new route ("catalog", new mvcroutehandler () {defaults = new routevaluedictionary (New {controller = "Products", Action = "list "})});

We can use this code to achieve our goal. It can help us implement/catalog or/catalog? Some = querystring, but the URLs such as/CATALOG/anythingelse cannot.

 

URL patterns match the path portion of a URL

 

Meet routevaluedictionary

A different technique to populateRoutevaluedictionaryIs to supplyIdictionary <string, Object>As a constructor parameter, or alternatively to use a collection initializer, as in the following example:

 
Routes. add (new route ("catalog", new mvcroutehandler () {defaults = new routevaluedictionary {"controller", "Products" },{ "action ", "list "}}});

 

Take a shortcut with maproute ()

ASP. net mvc adds an extension methodRoutecollection, CalledMaproute(). You will find this is much more convenient than using routes. Add (new route.

 
Routes. maproute ("publicproductslist", "catalog", new {controller = "Products", Action = "list "});

In this case,PublicproductslistIs the name of the route entry. It's just an arbitrary unique string. That's optional.

 

§ 8. 2.3 using parameters

As you 've seen several times already, parameters can be accepted via a curly brace syntax. as you can see before, the parameter can be placed in {}. Here we add a color parameter to the route:

Routes. maproute (null, "category/{color}", new {controller = "Products", Action = "list "});

This route will now match URLs such/CATALOG/yellowOr/CATALOG/1234, And the routing system will add a corresponding name/value pair to the request'sRoutedataObject. On a request to/CATALOG/yellow, for example,Routedata. Values ["color"] wocould be given the value yellow.

 

Logging ing parameter values in action Methods

You know that action methods can take parameters. when ASP. net MVC wants to call one of your action methods, it needs to supply a value for each method parameter. one of the places where it can get values isRoutedata collection. It will look in routedata's values dictionary, aiming to find a key/value pair whose name matches the parameter name.

We know that the action method can contain parameters. When MVC wants to call an action method, it needs to provide a value to the parameter of the method. The place where it obtains the value isRoutedata collection.It searches for a value corresponding to the parameter name in the routedata's key value pair.
So, if you have an action method like the following, its color parameter wocould be populated according to the {color} segment parsed from the incoming URL:

Therefore, if you have an action method like the following, its color parameter will be in {color} of the input URL.

Public actionresult list (string color) {// do something}

To be more precise, Action method parameters aren't simply taken directly from routedata. values, but instead are fetched viaModel binding system, Which is capable of instantiating and supplying objects of any. net type, including arrays and collections. you'll learn more about this mechanic in chapters 9 and 12. to be more accurate, the parameters of the Action method are not just simple and direct from routedata. obtain values. instead, it is obtained from the model binding system. net type. you will learn more in Chapter 9th and Chapter 12.

 

§ 8. 2.4 Using defaults

You didn't give a default value for {color}, so it became a mandatory parameter. the route entry no longer matches a request for/catalog. you can make the parameter optional by adding to your defaults object: In the above example, we didn't give {color} a default value, and it became a mandatory parameter. the route entry does not match the/CATALOG request. you can

 
Routes. maproute (null, "catalog/{color}", new {controller = "Products", Action = "list", color = (string) null });

In this way, the routes can match/category and/category/orange.

If you want a non-null default value, for example, if there is no null int, You can explicitly specify the value

Routes. add (new route ("catalog/{color}", new mvcroutehandler () {defaults = new routevaluedictionary (New {controller = "Products", Action = "list ", color = "beige", page = 1 })});

That's a perfectly fine thing to do; it's the correct way to set upRoutedataValues that are actually fixed for a givenRouteEntry. For example, for this route object,Routedata ["controller"]Will always equal "Products", regardless of the incoming URL, so matching requests will always be handled by productscontroller.

In this way, no matter what the entered URL is, the matching request will always be processed by productscontroller.

Remember that when you useMvcroutehandler(As you do by default in ASP. net MVC), you must have a value called Controller; otherwise, the Framework won't know what to do with the incoming request and will throw an error. the Controller value can come from a curly brace parameter in the URL, or can just be specified in the defaults object, but it cannot be omitted.

 

Creating optional parameters with no default value

Just like the default route configuration, we can specify the default value urlparameter. Optional.

 
Routes. maproute (null, "catalog/{page}", new {controller = "Products", Action = "list", page = urlparameter. optional });

In this way, when the accessed URL has a page value, we use the passed-In vallue. If not, we do not want any parameters in the Action method. you may wonder why 0 or null is not used as the default parameter. The following are two reasons:

  • If your action method takes a page parameter of Type int, then because that type can't hold null, you wowould have to supply the default value of 0 or some other int value. this means the action method wocould now always receive a legal value for page, so you wouldn't be able to control the default value using the MVC Framework's [defaultvalue] attribute or C #4's optional parameter syntax on the Action method itself (you'll learn more about these in the next chapter ).
  • If your action method has a page parameter of the int type, but it is a value type, it cannot be null. therefore, you need to provide a default value (0 or another value ). this means that the action method always requires a valid value. Therefore, if the action method uses [Defaultvalue] Feature or C #4Optional ParameterSyntax, you will not be able to control its type. (You will learn more in the next chapter)
  • Even if your action's page parameter was nullable, there's a further limitation. when binding incoming data to action method parameters, the MVC framework prioritizes routing parameter values above query string values (you'll learn more about value providers and model binding in Chapter 12 ). so, any routing value for page-even if it's null-wocould take priority and hide any query string value called page.
  • The page parameter of your action can be of the null type. there is a limit here. when the parameters of the Action method are of the binding type, the MVC framework takes precedence over the query string value. (you will learn about the value provider and model binding in Chapter 12 ). therefore, any route value set for the page, even if it is null, takes precedence over the query string that accesses the page.

Urlparameter. OptionalSolved these two problems

 

§ 8. 2.5 using Constraints

Sometimes, you want to add additional conditions to match specific route. For example:

    • You want to match the GET request instead of the POST request.
    • Some parameters must match specific parameters (the e.g. ID parameter must match the numeric type)
    • Some route are used to match requests sent by conventional Web browsers, and some match the same URL sent by the iPhone.

In these cases, you'll use the route's constraints Property

 

Matching against regular expressions

To ensure that the parameters are numeric, we use the following rule:

 
Routes. maproute (null, "articles/{ID}", new {controller = "articles", Action = "show "}, new {id = @ "\ D {1, 6 }"});

In this way, route will match the/articles/1 and/articles/123456 types, instead of other types. (here, the regular expression represents: Number type, 1 ~ 6)

 

Matching HTTP methods

If you want your route to match onlyGET requests(Not POST requests), you can use the built-in httpmethodconstraint class (it implements irouteconstraint)-for example:

Routes. maproute (null, "articles/{ID}", new {controller = "articles", Action = "show "}, new {httpmethod = new httpmethodconstraint ("get ")});

Put the HTTP method you want to match in the httpmethodconstraint constraint constructor, for example, new httpmethodconstraint ("get", "delete ").

Note thatHttpmethodconstraintAnd[Httpget] and [httppost]Irrelevant

 

Matching custom constraints

If none of the above can satisfy you, you can still implement it. for example, if you want to create a route entry that only allows web browsers to access, you can create the following constraints:

Public class useragentconstraint: irouteconstraint {private string _ requiredsubstring; Public useragentconstraint (string requiredsubstring) {This. _ requiredsubstring = requiredsubstring;} public bool match (httpcontextbase httpcontext, route, string paramname, routevaluedictionary values, routedirection) {If (httpcontext. request. useragent = NULL) return false; return httpcontext. request. useragent. contains (_ requiredsubstring );}}

The following routes can only match requests initiated by the iPhone:

Routes. add (new route ("articles/{ID}", new mvcroutehandler () {defaults = new routevaluedictionary (New {controller = "articles", Action = "show "}), constraints = new routevaluedictionary (New {id = @ "\ D {1, 6}", useragent = new useragentconstraint ("iPhone ")}});
 
 

§ 8. 2.6 prioritizing controllers by namespace

§ 8. 2.7 accepting a variable-length list of parameters

§ 8. 2.8 matching files on the server's hard disk

§ 8. 2.9 using ignoreroute to bypass the routing system
 
Public static void registerroutes (routecollection routes) {routes. ignoreroute ("{filename}. XYZ"); // rest of routing config goes here}

Here, {filename}. XYZ is treated as a URL pattern just like in a normal route entry, so in this example,
The routing system will now ignore any requests for/blah. XYZ or/Foo. XYZ? Some = querystring. (Of course,
You must place this entry higher in the route table than any other entry that wocould match and handle
Those URLs.) You can also pass a constraints parameter if you want tighter control over exactly which
URLs are ignored by routing.

Here {filename}. XYZ is treated as a URL model, just like a common route entry.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.