§8 URLs and Routing

Before ASP.NET MVC, the core assumption of routing in ASP.NET (just like
in many 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

图片 1

这样, 限制会很多, 有的人不想让人家知道自己文件的门路,


注:本文是【ASP.NET Web


§8.1 Putting the Programmer Back in Control

ASP.NET MVC打破了这种范围, since ASP.NET MVC’s requests are handled by
controller classes (compiled into a .NET assembly), there are no
particular files corresponding to incoming

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.

图片 2

This is all managed by the framework’s routing


§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.路径系统本来是给mvc自己用的,
所以路径代码是放在一个独门的程序集里(System.Web.Routing.dll in .NET
3.5, and simply System.Web.dll in .NET 4),而不是在System.Web.Mvc.dll


4.1 Routing in ASP.NET Web API 4.1 ASP.NET Web API中的路由


By Mike Wasson|February 11, 2012
作者:Mike Wasson | 日期:2012-2-11

This article describes how ASP.NET Web API routes HTTP requests to
本著作描述ASP.NET Web API怎么着将HTTP请求路由到控制器。

If you are familiar with ASP.NET MVC, Web API routing is very similar to
MVC routing. The main difference is that Web API uses the HTTP method,
not the URI path, to select the action. You can also use MVC-style
routing in Web API. This article does not assume any knowledge of
一旦您熟悉ASP.NET MVC,Web API路由与MVC路由特别像样。重要差异是Web
API中利用MVC风格的路由。本文不假使你具备ASP.NET MVC的其他文化。

 1 using System;
 2 using System.Collections.Generic;
 3 using System.Linq;
 4 using System.Web;
 5 using System.Web.Mvc;
 6 using System.Web.Routing;
 8 namespace MVCDemo
 9 {
10     public class RouteConfig
11     {
12         public static void RegisterRoutes(RouteCollection routes)
13         {
14             routes.MapMvcAttributeRoutes();//特性路由
16             routes.IgnoreRoute("{resource}.axd/{*pathInfo}");//忽略资源文件
18             routes.MapRoute(
19                 name: "Default",//路由名,唯一
20                 url: "{controller}/{action}/{id}",//路由URL
21                 defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional },//路由URL默认值
22                 namespaces: new[] { "MVCDemo.Controllers" },//命名空间避免二义性
23                 constraints: new { id = @"^\d*$" }//约束
25                 );
26         }
27     }
28 }

§8.2 Setting Up Routes

俺们来探视路径的布置, 在global.asax.cs文件里

    public class MvcApplication : System.Web.HttpApplication
        public static void RegisterRoutes(RouteCollection routes)
                "Default", // 路由名称
                "{controller}/{action}/{id}", // 带有参数的 URL
                new { controller = "Home", action = "Index", id = UrlParameter.Optional } // 参数默认值

        protected void Application_Start()

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
should know that this call to MapRoute() is just a concise alternative
to writing the following:当应用程序启动的时候,也就是Application_Start()鱼腥的时候, RegisterRoutes()静态方法会装入一个号称RouteTable.Routes的全局静态RouteCollection对象.
也是停放路径配置的地点.MapRoute是路径配置的进口, 为了简单的验证,

            Route myRoute = new Route("{controller}/{action}/{id}", new MvcRouteHandler())
                Defaults = new RouteValueDictionary(new
                    controller = "Home",
                    action = "Index",
                    id = UrlParameter.Optional
            routes.Add("Default", myRoute);


图片 3


§8.2.1  Understanding the Routing Mechanism

The routing mechanism 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.
早起的路由机制运作在框架的央求处理管道. 它的劳作就是运用进来的URL,
并用它来博取一个可知处理请求的的IHttpHandler 对象

Many 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 mechanism
powerfully to add extra behaviors across your whole

The Main Characters: RouteBase, Route, and RouteCollection


  • RouteBase is the abstract base class for a routing entry.
    You can implement unusual routing behaviors by deriving a custom
    type from it (I’ve included an example near the end of this
    chapter), but for now you can forget about it.
  • Route is 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.
  • A RouteCollection is a complete routing configuration. It’s
    an ordered list of RouteBase-derived objects (e.g., Route

How Routing Fits into the Request Processing Pipeline

When a URL is requested, the system invokes each of the IHttpModules
registered for the application. 当一个URL被呼吁,


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-specific
如若有个路由安排的黄金规则: 那么就是将非常路径放在一般路径的前边.
因为系统的分外由的算法是从最上端初阶, 而不是找最契合的.


§8.2.2  Adding a Route Entry

默认的路由是很普通的, 假设你想要处理其他类其它URL, 你还索要做一些手脚.
我来举个大概的例证, 比如我们想要用URL /Catalog来查看这些连串的装有产品

            routes.Add(new Route("Catalog", new MvcRouteHandler())
                Defaults = new RouteValueDictionary(
                new { controller = "Products", action = "List" }

我们得以用地点的这段代码来兑现我们的目标. 它可以援助我们贯彻/Catalog
或者是 /Catalog?some=querystring, 可是 /Catalog/Anythingelse


URL Patterns Match the Path Portion of a URL

图片 4


Meet RouteValueDictionary

A different technique to populate a RouteValueDictionary is to
supply an IDictionary<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 method to RouteCollection, called
MapRoute(). 你会发觉这比使用routes.Add(new Route(…)) 方便很多.

            routes.MapRoute("PublicProductsList", "Catalog",
                new { controller = "Products", action = "List" });

In this case, PublicProductsList is 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. 正像你前面看到的, 参数可以置身{}里,

            routes.MapRoute(null, "category/{color}",
               new { controller = "Products", action = "List" });

This route will now match URLs such as /Catalog/yellow or
/Catalog/1234, and the routing system will add a corresponding
name/value pair to the request’s RouteData object. On a request
to /Catalog/yellow, for example, RouteData.Values[“color”] would be
given the value yellow


Receiving 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
is the RouteData collection. It will look in RouteData’s Values
dictionary, aiming to find a key/value pair whose name matches the
parameter name.

俺们领略action方法可以带参数. 当mvc想要调用一个action方法,
它需要提供一个value给艺术的参数. 它拿走value的一个地方就是RouteData
So, if you have an action method like the following, its color
parameter would be populated according to the {color} segment parsed
from the incoming URL:

所以, 倘若你有个action方法像下边这样的,

        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 via the
model binding system, which is capable of instantiating and
supplying objects of any .NET type, including arrays and collections.
You’ll learn more about this mechanism in Chapters 9 and 12.
而是从模型绑定系统中赢得,各类.net类型. 你会在第9章和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:
在下边的例子中, 我们从未给{color}一个默认值, 它成为了一个恐吓的参数.
路由入口不再匹配/Catalog 请求. 你能够

            routes.MapRoute(null, "Catalog/{color}",
                new { controller = "Products", action = "List", color = (string)null });

这般, 路由就能匹配/Category和/Category/orange了.

要是你想要一个非null 的默认值, 比如没有null的 int, 你可以显式的指定值

            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 up
RouteData values that are actually fixed for a given Route
entry. 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

这般,不管输入的url是何等, 匹配请求总会被ProductsController处理.

Remember that when you use MvcRouteHandler (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

就像默认的路由配置, 大家可以指定默认值UrlParameter.Optional.

            routes.MapRoute(null, "Catalog/{page}",
                new { controller = "Products", action = "List", page = UrlParameter.Optional });

这样, 当访问的URL有page值的时候, 我们就应用传入的vallue, 假如没有,
为何不用0或者是null 作为默认参数, 上面是它的五个原因:

  • If your action method takes a page parameter of type int, then
    because that type can’t hold null, you would have to supply the
    default value of 0 or some other int value. This means the action
    method would 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).
  • 假诺您的action方法有个int类型的page参数,但是它是值类型,
    不可能是null. 所以你需要提供一个默认值(0或者是其他的值).
    这也认为着action方法总是需要一个法定的值, 所以,
  • 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—would take priority and hide any query
    string value called page.
  • 即时你的action的page参数可以是null类型. 这里还有个限制.
    当action方法的参数是binding类型的时候, mvc



§8.2.5  Using Constraints

有时候, 你会想要添加额外的标准化, 以分外特定的route. 比如:

  • 您想匹配get请求, 而不是post请求
  • 有的参数要配合特定的参数(e.g. ID参数必须配合数字类型)
  • 一对route用来匹配常规的web浏览器发来的央求,

In these cases, you’ll use the Route’s Constraints property


Matching Against Regular Expressions

为了保证参数是数字类型的, 我们采纳这样的条条框框:

            routes.MapRoute(null, "Articles/{id}",
                new { controller = "Articles", action = "Show" },
                new { id = @"\d{1,6}" });

如此, route就会匹配 /Articles/1 和 /Articles/123456 这两序列型,
而不是其余的,(这里的正则表达式表示的是: 数字类型,1~6个)


Matching HTTP Methods

If you want your Route to match only GET 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") });

你想匹配什么样的HTTP方法, 就把它内置HttpMethodConstraint构造器中,
比如,new HttpMethodConstraint(“GET”, “DELETE”).

您要专注的是 HttpMethodConstraint[HttpGet] and


Matching Custom Constraints

假定面前的二种都无法满意你, 那么你仍能实现它的.

        public class UserAgentConstraint : IRouteConstraint
            private string _requiredSubstring;
            public UserAgentConstraint(string requiredSubstring)
                this._requiredSubstring = requiredSubstring;
            public bool Match(HttpContextBase httpContext, Route route, string paramName,
            RouteValueDictionary values, RouteDirection routeDirection)
                if (httpContext.Request.UserAgent == null)
                    return false;
                return httpContext.Request.UserAgent.Contains(_requiredSubstring);


            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

§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)
    // 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 would 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.

这边{filename}.xyz 被用作一个URL模型, 就像一个一般的路由入口. 

Routing Tables 路由表

In ASP.NET Web API, a controller is a class that handles HTTP
requests. The public methods of the controller are called action
or simply actions. When the Web API framework receives a
request, it routes the request to an action.

To determine which action to invoke, the framework uses a routing table.
The Visual Studio project template for Web API creates a default
)。Visual Studio中Web API的门类模板会创制一个默认路由:

    name: "API Default", 
    routeTemplate: "api/{controller}/{id}", 
    defaults: new { id = RouteParameter.Optional } 

This route is defined in the WebApiConfig.cs file, which is placed in
the App_Start directory:

图片 5

图4-1. 项目中的WebApiConfig.cs配置文件

For more information aboout the WebApiConfig class, see Configuring
关于WebApiConfig类的更多音讯参考“配置ASP.NET Web
API”(本课程系列的第10章 — 译者注)。

If you self-host Web API, you must set the routing table directly on the
HttpSelfHostConfiguration object. For more information, see
Self-Host a Web
假定要自托管(self-host )Web
API”(本课程序列的第8章 — 译者注)。

Each entry in the routing table contains a route template. The default
route template for Web API is “api/{controller}/{id}”. In this template,
“api” is a literal path segment, and {controller} and {id} are
placeholder variables.
路由表中的每一个条目都蕴涵一个路由模板route template)。Web

When the Web API framework receives an HTTP request, it tries to match
the URI against one of the route templates in the routing table. If no
route matches, the client receives a 404 error. For example, the
following URIs match the default route:

  • /api/contacts
  • /api/contacts/1
  • /api/products/gizmo1

However, the following URI does not match, because it lacks the “api”

  • /contacts/1

Note: The reason for using “api” in the route is to avoid collisions
with ASP.NET MVC routing. That way, you can have “/contacts” go to an
MVC controller, and “/api/contacts” go to a Web API controller. Of
course, if you don’t like this convention, you can change the default
route table.

Once a matching route is found, Web API selects the controller and the
假如找到了匹配路由,Web API便会选取相应的主宰和动作:

  • To find the controller, Web API adds “Controller” to the value of
    the {controller} variable.
    — 译者注)。
  • To find the action, Web API looks at the HTTP method, and then looks
    for an action whose name begins with that HTTP method name. For
    example, with a GET request, Web API looks for an action that starts
    with “Get…”, such as “GetContact” or “GetAllContacts”. This
    convention applies only to GET, POST, PUT, and DELETE methods. You
    can enable other HTTP methods by using attributes on your
    controller. We’ll see an example of that later.
  • Other placeholder variables in the route template, such as {id}, are
    mapped to action parameters.

Let’s look at an example. Suppose that you define the following

public class ProductsController : ApiController 
    public void GetAllProducts() { } 
    public IEnumerable<Product> GetProductById(int id) { } 
    public HttpResponseMessage DeleteProduct(int id){ } 

Here are some possible HTTP requests, along with the action that gets
invoked for each:

HTTP Method
URI Path
GET api/products GetAllProducts (none)
GET api/products/4 GetProductById 4
DELETE api/products/4 DeleteProduct 4
POST api/products (no match)

Notice that the {id} segment of the URI, if present, is mapped to the
id parameter of the action. In this example, the controller defines
two GET methods, one with an id parameter and one with no parameters.

Also, note that the POST request will fail, because the controller does
not define a “Post…” method.


Routing Variations 路由变异

The previous section described the basic routing mechanism for ASP.NET
Web API. This section describes some variations.
上一节讲述了ASP.NET Web API基本的路由机制。本小节描述一些形成。


HTTP Methods HTTP方法

Instead of using the naming convention for HTTP methods, you can
explicitly specify the HTTP method for an action by decorating the
action method with the HttpGet, HttpPut, HttpPost, or
HttpDelete attribute.

In the following example, the FindProduct method is mapped to GET

public class ProductsController : ApiController 
    public Product FindProduct(id) {} 

To allow multiple HTTP methods for an action, or to allow HTTP methods
other than GET, PUT, POST, and DELETE, use the AcceptVerbs
attribute, which takes a list of HTTP methods.

public class ProductsController : ApiController 
    [AcceptVerbs("GET", "HEAD")]   // 指示该动作接收HTTP的GET和HEAD方法 — 译者注
    public Product FindProduct(id) { } 

    // WebDAV method
    // WebDAV方法(基于Web的分布式著作与版本控制的HTTP方法,是一个扩展的HTTP方法 — 译者注)
    [AcceptVerbs("MKCOL")]   // MKCOL是隶属于WebDAV的一个方法,它在URI指定的位置创建集合
    public void MakeCollection() { } 

 1.1 URI、URL和URN定义 

Routing by Action Name 通过动作名路由

With the default routing template, Web API uses the HTTP method to
select the action. However, you can also create a route where the action
name is included in the URI:

    name: "ActionApi", 
    routeTemplate: "api/{controller}/{action}/{id}", 
    defaults: new { id = RouteParameter.Optional } 

In this route template, the {action} parameter names the action method
on the controller. With this style of routing, use attributes to specify
the allowed HTTP methods. For example, suppose your controller has the
following method:

public class ProductsController : ApiController 
    public string Details(int id); 

In this case, a GET request for “api/products/details/1” would map to
the Details method. This style of routing is similar to ASP.NET MVC, and
may be appropriate for an RPC-style API.

You can override the action name by using the ActionName attribute.
In the following example, there are two actions that map to
“api/products/thumbnail/id”. One supports GET and the other supports

public class ProductsController : ApiController 
    public HttpResponseMessage GetThumbnailImage(int id); 

    public void AddThumbnailImage(int id); 

     URI(Uniform Resource

Non-Actions 非动作

To prevent a method from getting invoked as an action, use the
NonAction attribute. This signals to the framework that the method
is not an action, even if it would otherwise match the routing rules.

// Not an action method.
// 不是一个动作方法
public string GetPrivateData() { ... }

     URL (Uniform Resource

Further Reading 进一步读书

This topic provided a high-level view of routing. For more detail, see
Routing and Action
which describes exactly how the framework matches a URI to a route,
selects a controller, and then selects the action to invoke.



     URN(Uniform Resources

 1.2 URI、URL和URN三者之间的关联图

图片 6

1.3 对URI、URL和URN三者之间解析




1.4 URL应享有特色

     (1)  域名便于记念和拼写;

     (2)  简短;

     (3)  便于输入;

     (4)  可以反映出站点布局;


     (6)  持久、不可能改变

1.5  小结

 平常状态下,URI代表同意资源标识符(Uniform Resource


2 路由概述(传统路由)

2.1  WebForm URL与Route URL


 图片 7


2.2  ASP.NET 路由与 URL 重写

        ASP.NET 路由不同于其他 URL
重写方案。URL 重写通过在将请求发送到网页往日实际更改 URL
来处理传入请求。例如,一个应用 URL 重写的应用程序可能会将 URL 从 /Products/Widgets/ 更改为 /Products.aspx?id=4。此外,URL 重写平时没有相应的 API
来创设基于形式的 URL。在 URL 重写中,如若更改了 URL
形式,则必须手动更新包含原始 URL 的有着超链接。由于
ASP.NET 路由得以从 URL 提取值,所以拍卖传入请求时不更改
URL。就算非得创立一个 URL,则将参数值传递到为你生成 URL
的方法中。若要更改 URL

2.3  路由定义

        A route is a URL pattern that is mapped to a handler.
The handler can be a physical file, such as an .aspx file in a Web Forms
application. A handler can also be a class that processes the request,
such as a controller in an MVC application. To define a route, you
create an instance of the Route class by specifying the URL pattern, the
handler, and optionally a name for the route.


      You add the route to the
application by adding the Route object to the static Routes property of
the RouteTable class. The Routes property is a RouteCollection object
that stores all the routes for the application.You typically do not have
to write code to add routes in an MVC application. Visual Studio project
templates for MVC include preconfigured URL routes. These are defined in
the MvcApplication class, which is defined in the
Global.asax file.


2.4 URL Patterns(URL模式)

A URL pattern can contain literal values
and variable placeholders (referred to as URL
parameters). The literals and placeholders are located in segments of the URL which are delimited by the slash
(/) character.


When a request is made, the URL is parsed
into segments and placeholders, and the variable values are provided to
the request handler. This process is similar to the way the data in
query strings is parsed and passed to the request handler. In both cases
variable information is included in the URL and passed to the handler in
the form of key-value pairs. For query strings both the keys and the
values are in the URL. For routes, the keys are the placeholder names
defined in the URL pattern, and only the values are in the URL.


In a URL pattern, you define placeholders
by enclosing them in braces ( { and } ). You can define more than one
placeholder in a segment, but they must be separated by a literal value.
For example, {language}-{country}/{action} is a valid
route pattern. However, {language}{country}/{action} is not a valid pattern,
because there is no literal value or delimiter between the placeholders.
Therefore, routing cannot determine where to separate the value for
the language placeholder from the value for the country placeholder.


The following table shows valid route
patterns and examples of URL requests that match the patterns.


图片 8

 Typical URL Patterns in MVC


 URL patterns for routes in MVC
applications typically include {controller} and {action} placeholders.


When a request is received, it is routed
to the UrlRoutingModule object and then to the MvcHandler HTTP handler.
The MvcHandler HTTP handler determines which controller to invoke by
adding the suffix “Controller” to the controller value in the URL to
determine the type name of the controller that will handle the request.
The action value in the URL determines which action method to


For example, a URL that includes the URL
path /Products is mapped to a controller named ProductsController. The value in the action parameter is the name of the action method that
is called. A URL that includes the URL path /Products/show would result in a call to the Showmethod of the ProductsController class.

译文:例如,一个包含URL路径  /产品

The following table shows the default URL
patterns, and it shows examples of URL requests that are handled by the
default routes.


 图片 9

The route with the pattern {resource}.axd/{*pathInfo} is included to prevent requests
for the Web resource files such as WebResource.axd or ScriptResource.axd
from being passed to a controller.

For IIS 7.0, no file-name extension is
needed. For IIS 6.0, you must add the .mvc file-name extension to the
URL pattern, as in the following example:


 图片 10


图片 11

2.5 Adding Routes to a Web Forms

In a Web Forms application, you create
routes by using the MapPageRoute(String, String, String) method of the
RouteCollection class. The MapPageRoute method creates a Route object
and adds it to the RouteCollection object. You specify properties for
the Route object in parameters that you pass to the MapPageRoute


Typically, you add routes in a method
that is called from the handler for the Application_Start event in the
Global.asax file. This approach makes sure that the routes are available
when the application starts. It also enables you to call the method
directly when you unit-test the application. If you want to call a
method directly when you unit-test the application, the method that
registers the routes must be static (Shared in Visual Basic) and must
have a RouteCollection parameter.


The following example shows code from a
Global.asax file that adds a Route object that defines two URL
parameters named action and categoryName. URLs that have the specified
pattern are directed to the physical page named Categories.aspx.


protected void Application_Start(object sender, EventArgs e)

public static void RegisterRoutes(RouteCollection routes)

2.6 Adding Routes to an MVC

 If you adopt the MVC convention of
implementing controllers by creating classes that derive from the
ControllerBase class and giving them names that end with “Controller”,
you do not need to manually add routes in an MVC application. The
preconfigured routes will invoke the action methods that you implement
in the controller classes.


If you want to add custom routes in an
MVC application, you use the MapRoute(RouteCollection, String, String)
method instead of the MapPageRoute(String, String, String)

The following example shows the code that
creates default MVC routes in the Global.asax file, as defined in the
Visual Studio project template for MVC applications.


public class MvcApplication : System.Web.HttpApplication
    public static void RegisterRoutes(RouteCollection routes)

            "Default",                                              // Route name 
            "{controller}/{action}/{id}",                           // URL with parameters 
            new { controller = "Home", action = "Index", id = "" }  // Parameter defaults


    protected void Application_Start()

2.7 Setting Default Values for URL

When you define a route, you can assign a
default value for a parameter. The default value is used if a value for
that parameter is not included in the URL. You set default values for a
route by assigning a dictionary object to the Defaults property of the
Route class. The following example shows how to add a route that has
default values, by using the MapPageRoute(String, String, String,
Boolean, RouteValueDictionary) method.


void Application_Start(object sender, EventArgs e) 

public static void RegisterRoutes(RouteCollection routes)
        new RouteValueDictionary 
            {{"categoryName", "food"}, {"action", "show"}});

When ASP.NET routing handles a URL
request, the route definition shown in the example (with default values
of food for categoryName and showfor action) produces the results that
are listed in the following table.

图片 12

For MVC applications, overloads of the
RouteCollectionExtensions.MapRoute method, such as
MapRoute(RouteCollection, String, String, Object, Object), enable you to
specify defaults.

2.8 Handling a Variable Number of Segments
in a URL Pattern(在URL格局中拍卖可变多少的段)

Sometimes you have to handle URL requests
that contain a variable number of URL segments. When you define a route,
you can specify that if a URL has more segments than there are in the
pattern, the extra segments are considered to be part of the last
segment. To handle additional segments in this manner you mark the last
parameter with an asterisk (*). This is referred to
as a catch-all parameter. A route with a
catch-all parameter will also match URLs that do not contain any values
for the last parameter. The following example shows a route pattern that
matches an unknown number of segments.


/ query / { queryname } { * queryvalues

When ASP.NET routing handles a URL
request, the route definition shown in the example produces the results
that are listed in the following table.


图片 13

2.9  Adding Constraints to

In addition to matching a URL request to
a route definition by the number of parameters in the URL, you can
specify that values in the parameters meet certain constraints. If a URL
contains values that are outside the constraints for a route, that route
is not used to handle the request. You add constraints to make sure that
the URL parameters contain values that will work in your

Constraints are defined by using regular
expressions or by using objects that implement the IRouteConstraint
interface. When you add the route definition to the Routes collection,
you add constraints by creating a RouteValueDictionary object that
contains the verification test. The key in the dictionary identifies the
parameter that the constraint applies to. The value in the dictionary
can be either a string that represents a regular expression or an object
that implements the IRouteConstraint interface.

If you provide a string, routing treats
the string as a regular expression and checks whether the parameter
value is valid by calling the IsMatch method of the Regex class. The
regular expression is always treated as case-insensitive. For more
information, see .NET Framework Regular Expressions.

If you provide an IRouteConstraint
object, ASP.NET routing checks whether the parameter value is valid by
calling the Match method of the IRouteConstraint object. The Match
method returns a Boolean value that indicates whether the parameter
value is valid.

The following example shows how to use
the MapPageRoute method to create a route that has constraints that
limit what values can be included in the locale and year parameters. (In
an MVC application, you would use the MapRoute method.)



 1 public static void RegisterRoutes(RouteCollection routes)
 2 {
 3     routes.MapPageRoute("",
 4         "Category/{action}/{categoryName}",
 5         "~/categoriespage.aspx",
 6         true,
 7         new RouteValueDictionary 
 8             {{"categoryName", "food"}, {"action", "show"}},
 9         new RouteValueDictionary 
10             {{"locale", "[a-z]{2}-[a-z]{2}"},{"year", @"\d{4}"}}
11        );
12 }

When routing handles a URL request, the
route definition shown in the previous example produces the results that
are listed in the following table.

图片 14

 2.10 Scenarios When Routing Is Not

some circumstances, ASP.NET routing does not handle a request even when
is enabled for the Web site. This section describes some scenarios in
which routing does not handle the request.


A Physical File is Found that Matches
the URL Pattern(找到与URL格局匹配的物理文件)

By default, routing does not handle
requests that map to an existing physical file on the Web server. For
example, a request for
http://server/application/Products/Beverages/Coffee.aspx is not handled
by routing if a physical file exists at Products/Beverages/Coffee.aspx.
Routing does not handle the request even if it matches a defined
pattern, such as {controller}/{action}/{id}.

译文:默认情状下,路由不处理映射到Web服务器上幸存物理文件的乞求。例如,假使存在 Products/Beverages/Coffee.aspx.物理文件,请求http://server/application/Products/Beverages/Coffee.aspx
If you want routing to handle all
requests, even requests that point to files, you can override the
default behavior by setting the RouteExistingFiles property of the
RouteCollection object to true. When you set this value to true, all
requests that match a defined pattern are handled by routing.


Routing Is Explicitly Disabled for a
URL Pattern(为URL格局显式禁用路由)

You can
also specify that routing should not handle certain URL requests. You
prevent routing from handling certain requests by defining a route and
specifying that the StopRoutingHandler class should be used to handle
that pattern. When a request is handled by a StopRoutingHandler object,
the StopRoutingHandler object blocks any additional processing of the
request as a route. Instead, the request is processed as an ASP.NET
page, Web service, or other ASP.NET endpoint. You can use the
RouteCollection.Ignore method  

页面来处理的,网络页面,Web服务,或其他ASP.NET端点。您可以动用 RouteCollection.Ignore方法。

1 public static void RegisterRoutes(RouteCollection routes)
2 {
3   routes.Ignore("{resource}.axd/{*pathInfo}");
4 }

2.11 How URLs Are Matched to

When routing handles URL requests, it
tries to match the URL of the request to a route. Matching a URL request
to a route depends on all the following conditions:


  • The route patterns that you have
    defined or the default route patterns, if any, that are included in
    your project type. 

  • 译文:您已经定义的路由模式或默认的路由形式,要是有的话,它们包含在你的品各个类中。

  • The order in which you added them to
    the Routes collection.
  •  译文:您将它们增长到路由集合的一一。

  • Any default values that you have
    provided for a route.

  • 译文:您为某个路由提供的任何默认值。
  • Any constraints that you have
    provided for a route.

  • 译文:您为路径所提供的此外自律。

  • Whether you have defined routing to
    handle requests that match a physical file.

  • 译文:是否定义了路由来处理与物理文件匹配的请求。

For example, suppose that you add routes
with the following patterns:

   Route 1 is set to

   Route 2 is set to

译文:路线2设置为 products/show/{id}
Route 2 will never handle a request
because Route 1 is evaluated first, and it will always match requests
that could also work for Route 2. A request for
http://server/application/products/show/bikes seems to match Route 2
more closely, but it is handled by Route 1 with the following
controller is products.
action is show.
id is bikes.






Default values are used if a parameter is
missing from the request. Therefore, they can cause a route to match a
request that you did not expect. For example, suppose that you add
routes with the following patterns:
Route 1: {report}/{year}/{month}, with
default values for year and month.
Route 2: {report}/{year}, with a default
value for year.
Route 2 will never handle a request.
Route 1 might be intended for a monthly report, and Route 2 might be
intended for an annual report. However, the default values in Route 1
mean that it will match any request that could also work for Route






You can avoid ambiguity in the patterns
by including constants, such as annual/{report}/{year} and
If a URL does not match any Route object
that is defined in the RouteTable collection, ASP.NET routing does not
process the request. Instead, processing is passed to an ASP.NET page,
Web service, or other ASP.NET endpoint.

annual/{report}/{year} and monthly/{report}/{year}/{month}。

Page ,Web服务,或其余ASP.NET端点。

2.12 路由二义性



图片 15


图片 16图片 17

 1 using System;
 2 using System.Collections.Generic;
 3 using System.Linq;
 4 using System.Web;
 5 using System.Web.Mvc;
 6 using System.Web.Routing;
 8 namespace MVCDemo
 9 {
10     public class RouteConfig
11     {
12         public static void RegisterRoutes(RouteCollection routes)
13         {
14             routes.IgnoreRoute("{resource}.axd/{*pathInfo}"); 
16             routes.MapRoute(
17                 name: "Default", 
18                 url: "{controller}/{action}/{id}", 
19                 defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
21            );
22         }
23     }
24 }



图片 18图片 19

 1 using System;
 2 using System.Collections.Generic;
 3 using System.Linq;
 4 using System.Web;
 5 using System.Web.Mvc;
 7 namespace MVCDemo.Controllers
 8 {
 9     public class RouteDemoController : Controller
10     {
11         //
12         // GET: /RouteDemo/
13         public ActionResult Index()
14         {
15             return View();
16         }
17     }
18 }



图片 20图片 21

 1 using System;
 2 using System.Collections.Generic;
 3 using System.Linq;
 4 using System.Web;
 5 using System.Web.Mvc;
 7 namespace MVCDemo.Controllers.NewFolder1
 8 {
 9     public class RouteDemoController : Controller
10     {
11         //
12         // GET: /RouteDemo/
13         public ActionResult Index()
14         {
15             return Content("路由二义性测试");
16         }
17     }
18 }



图片 22

3 路由概述(特性路由)

 特性路由是在ASP.NET MVC
5中新增的,传统路由ASP.NET MVC 1中就有了。



图片 23


图片 24

3 路由生成URL


 3.1 URL生成的高层系概述


1  public  VirtualPathData GetVirtualPath(RequestContext requestContex,RouteValueDictionary values)
3  public  VirtualPathData GetVirtualPath(RequestContext requestContex,string name,RouteValueDictionary values)





  3.2  URL生成详解







图片 25


4 路由绑定到操作

MVC的一个特色了,它已经领先这些范围,如ASP.NET Dynamic

 4.1 高层次请求的路由管道







4.2 路由数量



5 路由调试

Manager Console窗口中运用NuGet安装即可,命令Install-Package

<add key="RouteDebugger:Enable" value="true'>




图片 26


图片 27

NuGet Packages”-“Online”输入”RouteDebugger”然后”Install”.

理所当然, 你也得以自己下载RouteDebugger.dll,
引用到web项目中, 然后手动在web.config中参预

<add key="RouteDebugger:Enabled" value="true" />



 1 using System;
 2 using System.Collections.Generic;
 3 using System.Linq;
 4 using System.Web;
 5 using System.Web.Mvc;
 6 using System.Web.Routing;
 8 namespace MVCDemo
 9 {
10     public class RouteConfig
11     {
12         public static void RegisterRoutes(RouteCollection routes)
13         {
14             routes.MapMvcAttributeRoutes();//
16             routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
18             routes.MapRoute(
19                 name: "Default",
20                 url: "{controller}/{action}/{id}",
21                 defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
22             );
23         }
24     }
25 }


 1 using System;
 2 using System.Collections.Generic;
 3 using System.Linq;
 4 using System.Web;
 5 using System.Web.Mvc;
 7 namespace MVCDemo.Controllers
 8 {
 9     public class RouteDemoController : Controller
10     {
11         //
12         // GET: /RouteDemo/
13         public ActionResult Index()
14         {
15             return View();
16         }
17     }
18 }


1 @inherits System.Web.Mvc.WebViewPage
3 <h2>RouteDebugger调试</h2>


图片 28

6 与路由有关的首要性命名空间和类

 6.1  路由涉及的命名空间

图片 29

 6.2 Class
Reference( 路由涉及到的重要类)

图片 30


7 总结


8 参考文献




【04】Professional Asp.net MVC 5













9   版权


  • 感谢您的读书,若有不足之处,欢迎指教,共同学习、共同提高。
  • 博主网址:http://www.cnblogs.com/wangjiming/。
  • 极少一些随笔利用读书、参考、引用、抄袭、复制和粘贴等多种方法结合而成的,大部分为原创。
  • 如您喜爱,麻烦推荐一下;如你有新想法,欢迎指出,邮箱:2016177728@qq.com。
  • 可以转载该博客,但无法不知名博客来源。