【ASP.NET 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;
 7 
 8 namespace MVCDemo
 9 {
10     public class RouteConfig
11     {
12         public static void RegisterRoutes(RouteCollection routes)
13         {
14             routes.MapMvcAttributeRoutes();//特性路由
15 
16             routes.IgnoreRoute("{resource}.axd/{*pathInfo}");//忽略资源文件
17 
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*$" }//约束
24 
25                 );
26         }
27     }
28 }

注:该例子没有投入区域

1 URI、URL与URN

 1.1 URI、URL和URN定义 

     URI(Uniform Resource
Identifier)代表联独资源标识符,标识资源的字符串;

     URL (Uniform Resource
Locator)代表统一资源定位符,互联网上正式资源的地方;

     URN(Uniform Resources
Name)代表联合营源名称,互联网上资源的名号;

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

图片 1

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

      本解析基于1.2
URI、URL和URN三者之间的涉嫌图。

     
(1)从命名角度,URI标识资源且唯一,URL标识资源地址
,URN标识资源名称;

     
(2)从数学关系:URI=URL+URN+URL∩URN;很简单看到,URL一定是URI,但URI不必然是URL,同理,URN一定是URI,但URI不自然是URN;

1.4 URL应负有特色

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

     (2)  简短;

     (3)  便于输入;

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

     (5)
 应该是“可破解的”,用户可以经过移除URL的最终,进而到达更高层次的音信体系布局;

     (6)  持久、不可以更改

1.5  小结

     
 平常状态下,URI代表同意资源标识符(Uniform Resource
Identifier)。URI是标识了一个资源的字符串。从技术角度看,所有URL都是URI。W3C认为“URL是一个业余的定义,但它那多少个有效:URL是URI的一体系型,它通过代表本身的根本走访机制来标识资源”,换句话说,URI是某种资源的标识符,而URL则为博得该资源提供了切实可行的新闻。

     
 注释:资源是一个抽象概念,既可以指一个文本,也可以指方法调用的结果或服务器上的部分其余内容。

2 路由概述(传统路由)

2.1  WebForm URL与Route URL

   
 (1)WebForm中,对URL的传入请求日常映射到磁盘上的物理文件,如.aspx文件。例如对http://server/application/Product.aspx?id=4的请求映射到名为Products.aspx文件,该文件包含代码和标记用于呈现对浏览器的响应,一般请求示过程抽象如下:

   
 图片 2

     (2)ASP.NET
MVC中,寻常地,URL映射并非映射到实际磁盘上的情理文件,那是按照ASP.NET路由特性,主要有八个进程,即URL映射和URL生成(接下去讲解)。在ASP.NET路由中,您可以定义URL情势,该格局涵盖在拍卖URL请求时利用的值的占位符。在运作时,运用程序名称前边的URL部分依据你所定义的URL格局分析为离散值。例如,在呼吁http://server/application/Products/show/beverages时,路由分析器可以将值Products、show和beverages传递给请求的处理程序。相反,在一个不由URL路由管理的请求中,/Products/show/beverages片段将被解释为运用程序中的一个文件的路径。
  

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.

     
 译文:路由是一种被映射到某个处理程序的URL格局。处理程序可能是一个物理文件,如在WebForms运用程序中的aspx文件。处理程序也说不定是一个处理请求的类,如MVC应用程序中的控制器。要定义路由,您可以经过点名URL方式、处理程序和路径的名目来创建路由类的实例。

      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.

     
译文:你可以经过将路由对象添加到RouteTable类的静态路由属性中的方式将路由添加到应用程序中。路由属性是一个为应用程序存储所有路由的路由对象。在MVC应用程序中,您日常不须求编制代码来添加路由。VS项目模板为MVC包括了事先计划的URL路由。那么些都是在MvcApplication类中定义的,被定义在Global.asac
文件中。

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.

译文:URL格局也许含有文字值和变量占位符(称为URL参数)。文字和占位符位于URL的一部分中,由斜杠(/)字符分隔。

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.

译文:当发出请求时,URL被分析为局地和占位符,且变量值被提须要请求处理程序。那一个进程看似于查询字符串中的数据被解析并传递给请求处理程序的主意。在那三种景况下,变量新闻都包蕴在URL中,并以键值对的花样传递给处理程序。对于查询字符串,键和值都在URL中。对于路由,键是URL情势中定义的占位符名称,在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.

译文:在URL情势中,通过将它们封装在括号(以及)中来定义占位符。您可以在一个段中定义多少个占位符,然而必须用文字值分隔它们。例如,语言-国家/行动是一种有效的不二法门形式。不过,语言国家/action不是一个可行的方式,因为占位符之间没有文字值或分隔符。由此,路由不可以控制将语言占位符的值与国家占位符的值分隔开。

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

下表显示了实用的路由方式和与情势匹配的URL请求示例。

图片 3

 Typical URL Patterns in MVC
Applications

译文:MVC运用程序中的经典格局

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

译文:在MVC运用程序中,路由URL格局寻常包涵控制器和动作占位符。

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
call.

译文:当接过到一个呼吁时,它被路由到UrlRoutingModule对象,然后发送到MvcHandler
HTTP处理程序。MvcHandler
HTTP处理程序通过向URL中的控制器值添加后缀“控制器”来规定要调用哪个控制器,以确定控制器的门类名称,该控制器将处理请求。URL中的操作值决定调用哪个操作方法。

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路径  /产品
的URL映射到一个名为ProductsController的控制器。action参数中的值是调用的操作方法的称谓。一个涵盖URL路径
  /产品/show
 的URL会导致对ProductsController类的Showmethod的调用。

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

译文:下表显示了默许的URL形式,它展现了由默许路由拍卖的URL请求的以身作则。

 图片 4

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:

译文:带有方式资源的路由axd/pathInfo,被用于防止Web资源文件的哀告,例如WebResource,axd或ScriptResource传递到控制器。对于IIS
7.0,不要求其余文件名称扩大。对于IIS
6.0,您必须添加.mvc文件扩大名到URL方式中,如上边的例证:

 图片 5

 如在VS2013使用MVC模板创制项目时,自动生成类RouteConfig.

图片 6

2.5 Adding Routes to a Web Forms
Application(添加路由到WebForm运用程序)

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
method.

译文:在Web
Forms应用程序中,您可以应用路由精选类的MapPageRoute(字符串、字符串、字符串)方法创造路由。MapPageRoute方法创制一个路由对象并将其添加到RouteCollection对象。您能够在传递给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.

译文:常常地,在大局Global.asax文件中,您可以在一个叫做Application_Start
方法里添加路由。该方法确保当应用程序启动时,路由是可以选取的。它还使您可以在对应用程序进行单元测试时间接调用该办法。如若您想在对应用程序进行单元测试时直接调用方法,那么注册路由的法子必须是静态的(在Visual
Basic中是共享的),并且必须具备一个路由参数。

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.

译文:上边的以身作则浮现了来自.Globalasax文件的代码,该代码添加了一个路由对象,该对象定义了多少个名为action和档次称号的URL参数。具有指定形式的url被定向到名为分类.aspx的大体页面。

protected void Application_Start(object sender, EventArgs e)
{
    RegisterRoutes(RouteTable.Routes);
}

public static void RegisterRoutes(RouteCollection routes)
{
    routes.MapPageRoute("",
        "Category/{action}/{categoryName}",
        "~/categoriespage.aspx");
}

2.6 Adding Routes to an MVC
Application

 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.

译文:若是您通过创办从控制器基类派生的类来落到实处控制器的MVC约定,并给它们以“控制器”结尾的名称,那么你就不要求在MVC应用程序中手动添加路由了。预配置的路由将调用您在决定器类中落到实处的操作方法。

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)
method.
译文:假如你想在MVC应用程序中添加自定义路由,您可以采取MapRoute(RouteCollection、String、String)方法,而不是MapPageRoute(字符串、字符串、字符串)方法。

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.

 译文:上面的事例显示了在大局中创设默许MVC路由的代码。asax文件,正如在Visual
Studio项目模板中定义的MVC应用程序。

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 = "" }  // Parameter defaults
        );

    }

    protected void Application_Start()
    {
        RegisterRoutes(RouteTable.Routes);
    }
}

2.7 Setting Default Values for URL
Parameters(为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.

译文:当您定义一个路由时,您可以为一个参数指定一个默许值。如若该参数的值没有包涵在URL中,则选用默许值。通过将dictionary对象分配给route类的默认属性,可以为路由设置默许值。上边的例证浮现了什么样通过动用MapPageRoute(字符串、字符串、字符串、布尔值、RouteValueDictionary)方法添加具有默许值的路由。

void Application_Start(object sender, EventArgs e) 
{
    RegisterRoutes(RouteTable.Routes);
}

public static void RegisterRoutes(RouteCollection routes)
{
    routes.MapPageRoute("",
        "Category/{action}/{categoryName}",
        "~/categoriespage.aspx",
        true,
        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.

图片 7

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.

译文:有时你必须处理包括一个可变多少的URL段的URL请求,其中。当您定义一个路由时,您可以指定,假如一个URL的一部分比方式中有越多的段,那么额外的段被认为是最终一局部的一局地。要以那种形式处理额外的段,您可以用星号(*)标记最终一个参数。那被誉为一个含糊的参数。一个涵盖所有参数的路由也将协作不分包最终一个参数的任何值的url。下边的以身作则体现了一个格外未知数量的段的路由形式。

/ 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.

译文:当ASP.NET路由拍卖一个URL请求时,示例中所示的路由定义暴发了下表中列出的结果。

图片 8

2.9  Adding Constraints to
Routes(为路由添加封锁)

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
application.

译文:除了通过URL中参数的数码来匹配URL请求外,还足以指定参数中的值满意特定的自律原则。假设一个URL包罗的值超过了路由的束缚,那么该路由就不会被用于拍卖请求。您添加了部分约束,以管教URL参数蕴涵在你的应用程序中工作的值。
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.

译文:约束是通过运用正则表明式或接纳达成IRouteConstraint接口的对象来定义的。当将路由定义添加到路由集合时,通过创建一个富含验证测试的RouteValueDictionary对象来丰裕约束。字典中的键标识约束应用到的参数。字典中的值可以是表示正则表明式的字符串,也足以是贯彻IRouteConstraint接口的对象。
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.

译文:如若你提供一个字符串,那么路由将字符串作为一个正则表明式来拍卖,并透过调用Regex类的IsMatch方法检查参数值是还是不是管用。正则表明式总是被视为不区分轻重缓急写的。要打听越来越多新闻,请参阅。净框架正则表达式。
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.

译文:借使您提供一个IRouteConstraint对象,ASP.NET
路由通过调用IRouteConstraint对象的万分方法,
以此来检查参数值是不是行得通。Match方法重返一个布尔值,该值表示参数值是不是有效。
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.)

译文:上边的以身作则突显了怎么运用MapPageRoute方法创立一条路子,该路由限制了地区和年参数中得以蕴含的值。(在MVC应用程序中,您将使用map路由艺术。)

 

 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.

图片 9

 2.10 Scenarios When Routing Is Not
Applied(不应用路由时的场景)

Under
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.

译文:在一些意况下,即使在Web站点启用时,ASP.NET
路由也不处理请求。本有的讲述了一些光景,其中路由不处理请求。

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
不被路由拍卖。就算它与已定义的情势相匹配,路由不处理请求,例如控制器/动作/id。
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.

译文:固然你想要路由拍卖所有请求,甚至指向文件的请求,您可以通过安装RouteCollection对象的习性RouteExistingFiles为true, 
以此来覆盖默许值。当您将那些值设置为true时,匹配定义形式的兼具请求都由路由拍卖。

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  

译文:您还足以指定路由不应有处理某些URL请求。通过定义一条路由,并指定StopRoutingHandler类应该用于拍卖该形式,从而幸免了拍卖某些请求的路由。当一个StopRoutingHandler对象处理请求时,StopRoutingHandler对象会阻塞请求作为路由的其余附加处理。相反,请求是作为ASP.NET
页面来拍卖的,网络页面,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
Routes(url如何与路由格外)

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:

译文:当路由拍卖URL请求时,它尝试将呼吁的URL与路由卓殊。将URL请求匹配到路由取决于以下标准:

  • 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
{controller}/{action}/{id}

   译文:
路径1设置为{controller}/{action}/{id}
   Route 2 is set to
products/show/{id}

 
译文:路线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
values:
controller is products.
action is show.
id is bikes.

译文:

路由2永远不会处理请求,因为路由1先是被匹配,它总是匹配可能在2号路径上工作的伏乞。请求http://server/application/products/show/bikes似乎比赛路线2更紧密,但它是由路线1以下值:

控制器products.

行动是show.

id是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
2.

译文:

一旦请求中匮乏一个参数,则动用默许值。因而,它们得以造成一条匹配您没有预料到的呼吁的路由。例如,若是您添加了以下形式:

路线1:报告/年/月,年和月默许值。

路线2:报告/年,年默许值。

路由2永远不会处理请求。第1条可能是本着每月报告的,而路由2可能是针对性年度报告的。不过,路由1中的默许值意味着它将卓殊任何可能用于路由2的请求。

You can avoid ambiguity in the patterns
by including constants, such as annual/{report}/{year} and
monthly/{report}/{year}/{month}.
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}。

设若URL不般配在RouteTable集合中定义的其它路由对象,ASP.NET路由不处理请求。相反,处理被传送给一个ASP.NET
Page ,Web服务,或其余ASP.NET端点。

2.12 路由二义性

只在同一个化解方案中,存在八个以及上述同等控制器下的相同action,当URL请求时,会晤世二义性。

二义性Demo目录结构

图片 10

RouteConfig.cs

图片 11图片 12

 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;
 7 
 8 namespace MVCDemo
 9 {
10     public class RouteConfig
11     {
12         public static void RegisterRoutes(RouteCollection routes)
13         {
14             routes.IgnoreRoute("{resource}.axd/{*pathInfo}"); 
15 
16             routes.MapRoute(
17                 name: "Default", 
18                 url: "{controller}/{action}/{id}", 
19                 defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
20                 
21            );
22         }
23     }
24 }
25                 

View
Code

/Controllers/RouteDemo

图片 13图片 14

 1 using System;
 2 using System.Collections.Generic;
 3 using System.Linq;
 4 using System.Web;
 5 using System.Web.Mvc;
 6 
 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 }

View
Code

/Controllers/NewFolder1/RouteDemo

图片 15图片 16

 1 using System;
 2 using System.Collections.Generic;
 3 using System.Linq;
 4 using System.Web;
 5 using System.Web.Mvc;
 6 
 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 }

View
Code

测试结果

图片 17

3 路由概述(特性路由)

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

 从内容上来看,特性路由的情节与观念路由大概,同样有路由URL、路由值、控制器路由、路由约束和路由默许值等。鉴于篇幅限制,在那边就概括的概述一下,不作详细阐释,前期有时间或者有意中人需求,再论述。

 定义:特性路由就是将路由URL定义在控制器上或控制器内的点子上,而不像传统路由将路由URL定义在RouteConfig.cs中。相比较如下

图片 18

 

图片 19

3 路由生成URL

 
 路由八个首要义务:匹配传入的URL请求和布局与一定路由对应的URL,概括之匹配URL和结构URL。在生成URL时,生成URL的情趣应该率先与选用用来生成URL的路由相匹配,这样路由就足以在处理传入或传播的URL时成为完全的双向系统。原则上,开发人员应该提供一组路由值,以便路由系统从中选中第二个可以匹配URL的路由。

 3.1 URL生成的高层系概述

 
路由的主导是一个卓殊不难的算法,该算法基于一个由RouteCollection类和RouteBase类组成的大约抽象对象。能够采用多种措施来生成URL,但这么些艺术皆以调用RouteCollection.GetVirtualPath的一个重载方法而截至。RouteCollection.GetVirtulPath方法公有三个重载版本,下边的代码显示它们的不二法门签名:

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

 第三个重载版本接受当前的RequestContext,以及由用户指定的路由值(字典)。

(1)路由集合通过RouteBase.GetVirtualPath方法遍历每个路由并走访:“可以扭转给定参数的URL吗”,这一个进程看似于在路由与传播请求匹配时所运用的匹配逻辑。

(2)倘若一个路由可以答应上边的题目(即匹配),那么它就会回到一个富含了URL的VirTualPathData实例以及其余匹配的音讯。否则,它就回来空值,路由体制移向列表中的下一个路由。

第三个重载接受多少个参数,其中第三个参数是路由名称。在路由集合中路由名称是唯一的,也就是说,没有多少个例外的路由具有同等的名称。当指定了路由名称时,路由集合就不必要循环遍历每个路由,相反,它可以及时找到指定名称的路由,并移向上面的手续(2)。即使找到的路由不能匹配指定的参数,该方法就会重回空值,并且不再匹配其余路由。

  3.2  URL生成详解

 
(1)开发人士调用像Html.ActionLink或Url.Action之类的措施,那个方法反过来再调用RouteCollection.GetVirtualPath方法,并向它传递一个RequestContext对象、一个分包值的字典以及用于选用生成URL的路由名称(可选参数)。

 (2)路由体制查看须求的路由参数(即没有提供路由参数的默许值),并保管提供的路由值字典为每一个渴求的参数提供一个值,否则,URL生成程序就会立马停下,并回到空值。

 (3)一些路由可能带有没有对应路由参数的默许值。如路由可能为category键提供默许值“pastries”,可是cateory不是路由URL的一个参数,那种景观下,倘使用户传入的路由值字典为category提供了一个值,那么该值必须匹配category的默许值。

 (4)然后路由系统使用路由约束。

(5)路由非凡成!现在可以通过查看每一个路由参数,并尝试运用字典中的对应值填充相应参数,进而生成URL。

可以包蕴为如下流程图:

图片 20

 

4 路由绑定到操作

 在这一章节,主要分析URL绑定到控制器操作的平底细节,分析底层原理,精通ASP.NET请求管道。注意,近年来路由不仅仅只是ASP.NET
MVC的一个表征了,它已经超先生越这么些限制,如ASP.NET Dynamic
Data。路由既不包蕴MVC的内部知识,也不依靠于MVC。

 4.1 高层次请求的路由管道

  当ASP.NET
处理请求时,路由管道紧要由以下几步组成:

 
 (1)UrlRoutingModule尝试使用在RouteTable中注册的路由匹配当前央浼。

 
 (2)若是RouteTable中有一个路由中标匹配,路由模块就会从匹配成功的路由中赢得IRouteHandler接口对象。

 
 (3)路由模块调用IRouteHandler接口的GetHandler方法,并回到用来处理请求的IHttpHandler对象。

 
 (4)调用HTTP处理程序中的ProcessRequest方法,然后把要拍卖的哀告传递给它

   (5)在ASP.NET
MVC中,IRouteHandler是MvcRouteHandler类的一个实例,MvcRouteHandler转而回到一个达成了IHttpHandler接口的MvcHandler对象。再次回到的MvcHandler对象主要用来实例化控制器,并调
       用该实例化的控制器上的操作方法。

4.2 路由数据

   
调用GetRouteData方法会重回RouteData的一个实例。RouteData中包涵了关于匹配请求的路由新闻。

   
如URL:{Controller}/{action}/{id}。当请求/albums/list/123传到时,该路由就会尝试匹配传入的哀告,若是同盟成功,它就创办一个字典,其中涵盖了从URL中剖析出的新闻。确切地讲,路由还会向Values字典中为URL中的每个路由参数添加一个键;对于传统路由{Controller}/{action}/{id},Values字典中应有至少含有七个键,分别是Controller,action和id,假设传入的URL是对/albums/list/123的伸手,路由就会分析该请求的URL,并为字典的键提供值。本例中,字典中“Controller”键的值为albums,”action”键的值为“list”,”id”键的值是“123”;对于特性路由MVC使用DataTokens字典来存储更可相信的信息,而不是操作名称字符串。具体来说,它包蕴一个操作描述符列表,那些描述符直接指向路由匹配时可能采用的操作方法。对于控制器级其他特色路由,列表元帅有不断一个操作。在全部MVC中都有应用的RequestContext的RouteData属性保存着外面路由值。

5 路由调试

 
 使用RouteDebugger调试,启用RouteDebugger后,它会用一个DebuggerRouteHandler替换所有路由处理程序,DebugRouteHandler截获所有传入的请求,并查询路由表中的每一个路由,以便在页面底部展现路由的诊断数据和参数。为使用RouteDebugger,只需在VS的Package
Manager Console窗口中使用NuGet安装即可,命令Install-Package
routedebugger.。RouteDebugger包在添加Route
Debugger程序集的还要。也在web.config文件的appSettings节点中添加一个安装,用来打开或禁用路由调试。

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

 只要启用RouteDebugger,它就显得从(在位置栏中)当前呼吁URL中领到的路由数据。如此,可以在地点栏中输入各个URL,并查看输入的URL能与哪些路由非常,在页面底部,它还会显得一个分包应用程序定义的所用路由列表,那样可以查阅定义的哪位路由可以与当下URL相匹配。

安装教程如下:

视图=>其余窗口=>程序包管理控制台

图片 21

在窗口中输入:Install-Package
routedebugger

图片 22

抑或也足以利用NuGet很有利的安装RouteDebugger,在品种方面右键-“Manage
NuGet Packages”-“Online”输入”RouteDebugger”然后”Install”.

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

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

测试结果

RouteConfig.cs

 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;
 7 
 8 namespace MVCDemo
 9 {
10     public class RouteConfig
11     {
12         public static void RegisterRoutes(RouteCollection routes)
13         {
14             routes.MapMvcAttributeRoutes();//
15 
16             routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
17 
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 }

RouteDemoController

 1 using System;
 2 using System.Collections.Generic;
 3 using System.Linq;
 4 using System.Web;
 5 using System.Web.Mvc;
 6 
 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 }

Index

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

 

图片 23

6 与路由相关的严重性命名空间和类

 6.1  路由涉及的命名空间

图片 24

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

图片 25

 

7 总结

 由于篇幅有限,路由章节就写到那,当然,还有众多内容没写,如路由布置文件、路由平安设置、自定义路由约束等,留给读者对象们去研讨吗。

8 参考文献

 【01】https://msdn.microsoft.com/en-us/library/cc668201.aspx\#setting\_default\_values\_for\_url\_parameters

【02】http://www.cnblogs.com/willick/p/3343105.html

【03】https://msdn.microsoft.com/zh-cn/library/cc668201(v=vs.100).aspx

【04】Professional Asp.net MVC 5

【05】http://www.cnblogs.com/liangxiaofeng/p/5620033.html

【06】https://msdn.microsoft.com/en-us/library/cc668177.aspx

【07】https://msdn.microsoft.com/en-us/library/dd535620.aspx

【08】https://msdn.microsoft.com/en-us/library/cc668176.aspx

【09】https://msdn.microsoft.com/en-us/library/dd329551.aspx

【10】https://msdn.microsoft.com/en-us/library/system.web.routing.route.aspx

【11】https://msdn.microsoft.com/en-us/library/system.web.routing.pageroutehandler.aspx

【12】https://msdn.microsoft.com/en-us/library/system.web.mvc.mvcroutehandler.aspx

【13】https://msdn.microsoft.com/en-us/library/system.web.ui.page.routedata.aspx

【14】https://msdn.microsoft.com/en-us/library/bb398900.aspx

【15】https://msdn.microsoft.com/en-us/library/ee941656.aspx

 

9   版权

 

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