美学原理【ASP.NET MVC连串】浅谈ASP.NET MVC 路由

译文:假诺你通过创制从控制器基类派生的类来贯彻控制器的MVC约定,并给它们以“控制器”结尾的称号,那么您就不需要在MVC应用程序中手动添加路由了。预配置的路由将调用您在支配器类中实现的操作方法。

3 路由生成URL

 

2.7 Setting Default Values for URL
Parameters(为URL参数设置默认值)

  3.2  URL生成详解

美学原理 1美学原理 2

译文:在URL情势中,通过将它们封装在括号(以及)中来定义占位符。您可以在一个段中定义几个占位符,但是必须用文字值分隔它们。例如,语言-国家/行动是一种有效的路线情势。不过,语言国家/action不是一个实惠的形式,因为占位符之间没有文字值或分隔符。由此,路由不可能说了算将语言占位符的值与国家占位符的值分隔开。

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

美学原理 3

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.

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

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

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

美学原理 4

2.3  路由定义

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

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

     
 注释:资源是一个抽象概念,既可以指一个文本,也足以指方法调用的结果或服务器上的一部分另外情节。

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.

/Controllers/RouteDemo

3 路由概述(特性路由)

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

 Typical URL Patterns in MVC
Applications

美学原理 5

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

1.5  小结

译文:平常地,在全局Global.asax文件中,您可以在一个叫做Application_Start
方法里添加路由。该方法确保当应用程序启动时,路由是能够动用的。它还使您可以在对应用程序举行单元测试时从来调用该办法。假使你想在对应用程序举办单元测试时一直调用方法,那么注册路由的不二法门必须是静态的(在Visual
Basic中是共享的),并且必须有所一个路由参数。

 
 (1)UrlRoutingModule尝试使用在RouteTable中登记的路由匹配当前呼吁。

美学原理,(5)路由优异成!现在可以因而翻看每一个路由参数,并尝试接纳字典中的对应值填充相应参数,进而生成URL。

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

译文:假设您提供一个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.)

译文:带有形式资源的路由axd/pathInfo,被用来制止Web资源文件的央浼,例如WebResource,axd或ScriptResource传递到控制器。对于IIS
7.0,不需要此外文件名称扩张。对于IIS
6.0,您必须添加.mvc文件扩张名到URL情势中,如下面的例证:

     (3)  便于输入;

译文:在一些情状下,尽管在Web站点启用时,ASP.NET
路由也不处理请求。本有的讲述了一些气象,其中路由不处理请求。

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

   
如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属性保存着外面路由值。

 1.1 URI、URL和URN定义 

美学原理 6

View
Code

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

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

美学原理 7

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);
    }
}
1  public  VirtualPathData GetVirtualPath(RequestContext requestContex,RouteValueDictionary values)
2 
3  public  VirtualPathData GetVirtualPath(RequestContext requestContex,string name,RouteValueDictionary values)

译文:当发出请求时,URL被分析为部分和占位符,且变量值被提供给请求处理程序。这么些历程看似于查询字符串中的数据被分析并传递给请求处理程序的措施。在这二种意况下,变量新闻都饱含在URL中,并以键值对的花样传递给处理程序。对于查询字符串,键和值都在URL中。对于路由,键是URL形式中定义的占位符名称,在URL中单独是值。

     (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.12 路由二义性

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

 

 只要启用RouteDebugger,它就显示从(在地方栏中)当前呼吁URL中领取的路由数据。如此,能够在地方栏中输入各个URL,并查阅输入的URL能与哪些路由卓殊,在页面底部,它还会显示一个富含应用程序定义的所用路由列表,这样可以查看定义的哪位路由可以与当前URL相匹配。

美学原理 8

二义性Demo目录结构

美学原理 9

4 路由绑定到操作

译文:在MVC运用程序中,路由URL情势平日包含控制器和动作占位符。

美学原理 10

只要请求中缺失一个参数,则使用默认值。因而,它们能够引致一条匹配您没有预料到的乞求的路由。例如,假设您添加了以下形式:

美学原理 11美学原理 12

5 路由调试

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

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

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.

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

RouteConfig.cs

译文:例如,假如您添加了以下格局:
   Route 1 is set to
{controller}/{action}/{id}

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

 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 }

译文:下边的示范显示了什么样运用MapPageRoute方法创制一条路径,该路由限制了地段和年参数中可以涵盖的值。(在MVC应用程序中,您将利用map路由艺术。)

设置教程如下:

  • 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.
  •  译文:您将它们增长到路由集合的相继。

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.

Index

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

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

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.

 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 }
 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 }

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

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

译文:

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

注:该例子没有出席区域

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

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

   
 美学原理 13

2 路由概述(传统路由)

2.8 Handling a Variable Number of Segments
in a URL Pattern(在URL情势中处理可变多少的段)

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

美学原理 14

译文:假诺您提供一个字符串,那么路由将字符串作为一个正则表明式来拍卖,并透过调用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.

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"}});
}

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

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

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

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

 
 路由五个紧要职责:匹配传入的URL请求和布局与一定路由对应的URL,概括之匹配URL和结构URL。在生成URL时,生成URL的情致应该率先与采用用来生成URL的路由相匹配,这样路由就可以在拍卖传入或传播的URL时成为全体的双向系统。原则上,开发人士应该提供一组路由值,以便路由系统从中选中第一个可以匹配URL的路由。

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

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

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.

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

     
 通常状态下,URI代表同意资源标识符(Uniform Resource
Identifier)。URI是标识了一个资源的字符串。从技术角度看,所有URL都是URI。W3C认为“URL是一个业余的定义,但它特别实用:URL是URI的一种档次,它通过代表我的最首要走访机制来标识资源”,换句话说,URI是某种资源的标识符,而URL则为得到该资源提供了现实的信息。

8 参考文献

/Controllers/NewFolder1/RouteDemo

4.2 路由数量

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

译文:下边的演示显示了来自.Globalasax文件的代码,该代码添加了一个路由对象,该对象定义了六个名为action和品种称号的URL参数。具有指定情势的url被定向到名为分类.aspx的情理页面。

7 总结

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.

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

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.

美学原理 15美学原理 16

1 URI、URL与URN

美学原理 17

 
(1)开发人士调用像Html.ActionLink或Url.Action之类的主意,这么些艺术反过来再调用RouteCollection.GetVirtualPath方法,并向它传递一个RequestContext对象、一个含有值的字典以及用于选拔生成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:

View
Code

 在这一章节,紧要分析URL绑定到控制器操作的最底层细节,分析底层原理,精晓ASP.NET请求管道。注意,如今路由不仅仅只是ASP.NET
MVC的一个特性了,它早已抢先这些限制,如ASP.NET Dynamic
Data。路由既不包括MVC的里边知识,也不借助于MVC。

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

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

译文:在Web
Forms应用程序中,您可以利用路由精选类的MapPageRoute(字符串、字符串、字符串)方法创立路由。MapPageRoute方法创制一个路由对象并将其添加到RouteCollection对象。您可以在传递给MapPageRoute方法的参数中指定路由对象的特性。

美学原理 18

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.

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

 
路由的主干是一个非常简单的算法,该算法基于一个由RouteCollection类和RouteBase类组成的简易抽象对象。可以应用多种主意来生成URL,但那些措施都以调用RouteCollection.GetVirtualPath的一个重载方法而终结。RouteCollection.GetVirtulPath方法公有两个重载版本,下边的代码展示它们的点子签名:

美学原理 19

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

 
 (2)假如RouteTable中有一个路由成功匹配,路由模块就会从匹配成功的路由中获取IRouteHandler接口对象。

 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 }

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.

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

 如在VS2013选取MVC模板创造项目时,自动生成类RouteConfig.

译文:当路由拍卖URL请求时,它尝试将呼吁的URL与路由非凡。将URL请求匹配到路由取决于以下原则:

 由于篇幅有限,路由章节就写到这,当然,还有为数不少内容没写,如路由安排文件、路由平安设置、自定义路由约束等,留给读者对象们去探讨吗。

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

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

译文:URL形式也许带有文字值和变量占位符(称为URL参数)。文字和占位符位于URL的有些中,由斜杠(/)字符分隔。

 先看看如下例子,你能完全清楚啊?

美学原理 20

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

 4.1 高层次请求的路由管道

      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永远不会处理请求。第1条可能是针对性每月报告的,而路由2恐怕是指向年度报告的。然则,路由1中的默认值意味着它将很是任何可能用于路由2的伏乞。

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.

id是bikes.

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

  • 译文:您为路径所提供的任何自律。

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

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

   
调用GetRouteData方法会再次回到RouteData的一个实例。RouteData中带有了有关匹配请求的路由音信。

控制器products.

9   版权

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

        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.

 3.1 URL生成的高层系概述

只在同一个解决方案中,存在多少个以及上述同等控制器下的相同action,当URL请求时,会油不过生二义性。

2.1  WebForm URL与Route 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.

        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
形式,请在某地方变动该情势,您在应用程序中开创的基于该情势的兼具链接将机关使用新情势。

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

 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 }

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

1.4 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  

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

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

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

 定义:特性路由就是将路由URL定义在控制器上或控制器内的主意上,而不像传统路由将路由URL定义在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.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                 

测试结果

 美学原理 21

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

 

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.

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.

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

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

译文:除了通过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.

     (6)  持久、不可能更改

(2)假如一个路由能够回答下边的题目(即匹配),那么它就会回来一个含有了URL的VirTualPathData实例以及其余匹配的消息。否则,它就再次来到空值,路由体制移向列表中的下一个路由。

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

美学原理 22

6 与路由相关的基本点命名空间和类

译文:当你定义一个路由时,您可以为一个参数指定一个默认值。假诺该参数的值没有包含在URL中,则使用默认值。通过将dictionary对象分配给route类的默认属性,可以为路由安装默认值。上面的例子显示了何等通过使用MapPageRoute(字符串、字符串、字符串、布尔值、RouteValueDictionary)方法添加具有默认值的路由。

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

可以概括为如下流程图:

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.

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

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

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

 

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

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

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

     (5)
 应该是“可破解的”,用户能够经过移除URL的最终,进而到达更高层次的信息连串布局;

其次个重载接受六个参数,其中第二个参数是路由名称。在路由集合中路由名称是唯一的,也就是说,没有多少个不同的路由具有相同的称呼。当指定了路由名称时,路由集合就不需要循环遍历每个路由,相反,它可以立时找到指定名称的路由,并移向下边的手续(2)。假使找到的路由无法匹配指定的参数,该方法就会回来空值,并且不再匹配其他路由。

2.4 URL Patterns(URL模式)

 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 }

 译文:下边的例子体现了在大局中创建默认MVC路由的代码。asax文件,正如在Visual
Studio项目模板中定义的MVC应用程序。

2.2  ASP.NET 路由与 URL 重写

译文:例如,一个带有URL路径  /产品
的URL映射到一个名为ProductsController的控制器。action参数中的值是调用的操作方法的名号。一个蕴含URL路径
  /产品/show
 的URL会促成对ProductsController类的Showmethod的调用。

比方URL不配合在RouteTable集合中定义的另外路由对象,ASP.NET路由不处理请求。相反,处理被传送给一个ASP.NET
Page ,Web服务,或另外ASP.NET端点。

下表展现了卓有功能的路由情势和与形式匹配的URL请求示例。

     
译文:你可以经过将路由对象添加到RouteTable类的静态路由属性中的情势将路由添加到应用程序中。路由属性是一个为应用程序存储所有路由的路由对象。在MVC应用程序中,您平日不需要编制代码来添加路由。VS项目模板为MVC包含了事先布置的URL路由。这个都是在MvcApplication类中定义的,被定义在Global.asac
文件中。

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

行动是show.

 

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.

2.6 Adding Routes to an MVC
Application

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

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

RouteDemoController

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.

 美学原理 23

View
Code

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

 

RouteConfig.cs

译文:下表展现了默认的URL情势,它显得了由默认路由拍卖的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请求。通过定义一条路由,并指定StopRoutingHandler类应该用于拍卖该形式,从而避免了拍卖某些请求的路由。当一个StopRoutingHandler对象处理请求时,StopRoutingHandler对象会卡住请求作为路由的另外附加处理。相反,请求是当做ASP.NET
页面来拍卖的,网络页面,Web服务,或任何ASP.NET端点。您可以行使 RouteCollection.Ignore方法。

在窗口中输入:Install-Package
routedebugger

 6.1  路由涉及的命名空间

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

译文:倘若您想要路由拍卖所有请求,甚至指向文件的哀告,您可以经过设置RouteCollection对象的特性RouteExistingFiles为true, 
以此来覆盖默认值。当你将以此值设置为true时,匹配定义格局的拥有请求都由路由拍卖。

 
译文:路线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.

美学原理 24

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

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

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

     (2)  简短;

译文:有时你必须处理包含一个可变多少的URL段的URL请求,其中。当您定义一个路由时,您可以指定,尽管一个URL的一些比情势中有更多的段,那么额外的段被认为是最终一有的的一有的。要以这种措施处理额外的段,您可以用星号(*)标记最终一个参数。这被誉为一个暧昧的参数。一个涵盖所有参数的路由也将匹配不包含最后一个参数的任何值的url。下边的以身作则显示了一个很是未知数量的段的路由格局。

译文:默认情况下,路由不处理映射到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.

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

事例引入

 (2)路由体制查看要求的路由参数(即没有提供路由参数的默认值),并保证提供的路由值字典为每一个渴求的参数提供一个值,否则,URL生成程序就会应声为止,并赶回空值。

/ query / { queryname } { * queryvalues
}

 

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

美学原理 25

2.11 How URLs Are Matched to
Routes(url怎样与路由分外)

【04】Professional Asp.net MVC 5

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:

译文:您可以因此包含常量来避免格局中的歧义,例如
annual/{report}/{year} and monthly/{report}/{year}/{month}。

测试结果