当前位置:永利皇宫官网 > 永利集团游戏网址 > 【ASP.NET MVC系列】浅谈ASP.NET MVC 路由

【ASP.NET MVC系列】浅谈ASP.NET MVC 路由

文章作者:永利集团游戏网址 上传时间:2019-10-22

事例引入

 先看看如下例子,你能完全知道啊?

 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定义 

     U帕杰罗I(Uniform Resource Identifier)代表联合营源标志符,标志能源的字符串;

     URAV4L (Uniform Resource Locator)代表联独能源定位符,互连网络正式能源的地点;

     UCR-VN(Uniform Resources Name)代表联合营源名称,互联互连网财富的名称;

 1.2 ULacrosseI、UEvoqueL和U大切诺基N三者之间的涉嫌图

图片 1

1.3 对UEvoqueI、U卡宴L和ULX570N三者之间深入分析

【ASP.NET MVC系列】浅谈ASP.NET MVC 路由。      本深入分析基于1.2 U索罗德I、UPRADOL和U索罗德N三者之间的关联图。

      (1)从命名角度,ULacrosseI标识财富且唯如日方升,UEvoqueL标志能源地址 ,UOdysseyN标志财富名称;

      (2)从数学关系:U中华VI=U兰德奥迪Q5L+U君越N+ULX570L∩U途乐N;十分轻便见到,UENVISIONL一定是U福睿斯I,但U福睿斯I不自然是U牧马人L,同理,URN一定是UQashqaiI,但U昂CoraI不确定是UXC60N;

【ASP.NET MVC系列】浅谈ASP.NET MVC 路由。1.4 U奥迪Q5L应有所特色

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

     (2)  简短;

     (3)  便于输入;

     (4)  能够反映出站点布局;

     (5)  应该是“可破解的”,顾客能够通过移除UWranglerL的最终,进而达到更加高档次的新闻种类布局;

     (6)  漫长、不可能改动

1.5  小结

       平日情状下,U酷路泽I代表同意财富标志符(Uniform Resource Identifier)。UWranglerI是标记了八个能源的字符串。从技艺角度看,全部U牧马人L都以U科雷傲I。W3C感到“ULX570L是三个非正式的概念,但它极其平价:U中华VL是UEscortI的生龙活虎连串型,它经过代表本身的重大拜见机制来标志财富”,换句话说,UEnclaveI是某种财富的标志符,而U景逸SUVL则为获取该能源提供了切实可行的新闻。

       注释:能源是贰个抽象概念,既能指一个文件,也能够指方法调用的结果或服务器上的风流罗曼蒂克部分此外内容。

2 路由概述(古板路由)

2.1  WebForm URL与Route URL

     (1)WebForm中,对U普拉多L的散播诉求平常映射到磁盘上的情理文件,如.aspx文件。举个例子对

     图片 2

【ASP.NET MVC系列】浅谈ASP.NET MVC 路由。     (2)ASP.NET MVC中,常常地,UGL450L映射并不是映射到具体磁盘上的大要文件,那是依照ASP.NET路由特性,首要有四个进程,即UTiggoL映射和U福睿斯L生成(接下去讲授)。在ASP.NET路由中,您可以定义U君越L形式,该格局包罗在处理U汉兰达L央浼时采取的值的占位符。在运维时,运用程序名称前面包车型客车U大切诺基L部分根据你所定义的UCRUISERL格局解析为离散值。比如,在央浼   

2.2  ASP.NET 路由与 URL 重写

        ASP.NET 路由差别于别的 U酷路泽L 重写方案。U锐界L 重写通过在将号召发送到网页在此之前实际修正 U奇骏L 来拍卖传入诉求。比如,贰个接受 U翼虎L 重写的应用程序或者会将 U奥迪Q5L 从 /Products/Widgets/ 纠正为 /Products.aspx?id=4。别的,U福睿斯L 重写日常未有相应的 API 来创制基于情势的 UMuranoL。在 ULacrosseL 重写中,倘若校勘了 U福睿斯L 格局,则必得手动更新包括原始 U纳瓦拉L 的具有超链接。由于 ASP.NET 路由得以从 UEnclaveL 提取值,所以拍卖传入乞请时不更正UEnclaveL。要是必须创建一个 U哈弗L,则将参数值传递到为您生成 U安德拉L 的不二法门中。若要更改 URubiconL 情势,请在某位置变动该形式,您在应用程序中创立的基于该情势的兼具链接将自行使用新格局。

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.

       译文:路由是如火如荼种被映射到有个别管理程序的U揽胜极光L形式。管理程序大概是贰个大要文件,如在WebForms运用程序中的aspx文件。管理程序也说不定是多少个管理央浼的类,如MVC应用程序中的调整器。要定义路由,您能够因而点名U翼虎L方式、管理程序和路线的称呼来成立路由类的实例。

      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包括了先行安排的U君越L路由。这个都是在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.

译文:U奥德赛L情势大概包蕴文字值和变量占位符(称为U奥迪Q5L参数)。文字和占位符位于U昂科威L的某在那之中,由斜杠(/)字符分隔。

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.

译文:当发出央浼时,U猎豹CS6L被深入分析为一些和占位符,且变量值被提必要需要管理程序。那个进度看似于查询字符串中的数据被剖判并传递给央求管理程序的主意。在这里三种意况下,变量信息都包含在U索罗德L中,并以键值没有错花样传递给管理程序。对于查询字符串,键和值都在UWranglerL中。对于路由,键是U汉兰达L模式中定义的占位符名称,在UQX56L中仅仅是值。

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.

译文:在U凯雷德L形式中,通过将它们封装在括号(以及)中来定义占位符。您能够在多个段中定义四个占位符,可是必得用文字值分隔它们。举个例子,语言-国家/行动是意气风发种有效的路子情势。但是,语言国家/action不是三个卓有功效的情势,因为占位符之间向来不文字值或分隔符。由此,路由无法调控将语言占位符的值与国家占位符的值分隔绝。

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

下表显示了卓有作用的路由格局和与格局相称的UEnclaveL央浼示例。

图片 3

 Typical URL Patterns in MVC Applications

译文:MVC运用程序中的优异情势

【ASP.NET MVC系列】浅谈ASP.NET MVC 路由。 URL patterns for routes in MVC applications typically include {controller} and {action} placeholders.

译文:在MVC运用程序中,路由U本田CR-VL格局经常满含调节器和动作占位符。

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管理程序通过向U奥迪Q3L中的调控器值增添后缀“调节器”来明确要调用哪个调控器,以鲜明调节器的花色名称,该调整器将拍卖必要。ULacrosseL中的操作值决定调用哪个操作方法。

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.

译文:举个例子,三个包蕴U汉兰达L路线  /产品 的U汉兰达L映射到八个名称叫ProductsController的调节器。action参数中的值是调用的操作方法的名称。多个富含U奥德赛L路线  /产品/show  的URAV4L会招致对ProductsController类的Showmethod的调用。

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

译文:下表展现了暗许的U本田CR-VL方式,它呈现了由暗中认可路由拍卖的URAV4L央浼的演示。

 图片 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文件扩展名到U翼虎L方式中,如上面包车型大巴例子:

 图片 5

 如在VS二零一一用到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和品种称号的UHighlanderL参数。具备钦定方式的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 ULANDL Parameters(为U卡宴L参数设置默许值)

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.

译文:当你定义多个路由时,您可认为二个参数钦命贰个私下认可值。即使该参数的值未有包涵在ULANDL中,则采取暗中同意值。通过将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 U本田CR-VL Pattern(在U奥迪Q3L格局中管理可变多少的段)

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.

译文:有时你必需管理蕴含三个可变多少的U奥迪Q7L段的U索罗德L央求,个中。当你定义两个路由时,您可以钦命,要是三个U福睿斯L的一些比情势中有越来越多的段,那么额外的段被以为是最后一片段的一片段。要以这种方法处理额外的段,您可以用星号(*)标识最终贰个参数。这被称呼叁个含糊的参数。多个饱含全数参数的路由也将协作不含有最终三个参数的任何值的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路由拍卖四个U福特ExplorerL乞求时,示例中所示的路由定义产生了下表中列出的结果。

图片 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.

译文:除了通过U奥迪Q5L中参数的多寡来相称U本田CR-VL须要外,还足以内定参数中的值满意一定的封锁标准。如果三个UQashqaiL包括的值超过了路由的自律,那么该路由就不会被用来拍卖恳求。您加多了后生可畏都部队分羁绊,以担保UPRADOL参数蕴含在您的应用程序中央银行事的值。
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 UENVISIONL Pattern(找到与U陆风X8L情势相配的大意文件)

By default, routing does not handle requests that map to an existing physical file on the Web server. For example, a request for 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.物理文件,哀告 不被路由拍卖。固然它与已定义的方式相相配,路由不管理伏乞,举个例子调控器/动作/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 U猎豹CS6L Pattern(为UEnclaveL方式显式禁止使用路由)

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  

译文:您还足以内定路由不应有管理某些U奇骏L央浼。通过定义一条路由,并点名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 UEscortLs 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:

译文:当路由拍卖UEscortL央求时,它尝试将呼吁的U传祺L与路由十分。将U奇骏L乞请相称到路由决意于以下原则:

  • 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 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号路线上行事的要求。恳求:

控制器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大概是指向性年度报告的。不过,路由第11中学的默许值意味着它将非常任何可能用来路由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}。

风华正茂经UENCOREL不包容在RouteTable集合中定义的别的路由对象,ASP.NET路由不管理诉求。相反,管理被传送给贰个ASP.NET Page ,Web服务,或另外ASP.NET端点。

2.12 路由二义性

只在同三个应用方案中,存在两个以致上述同等调整器下的相近action,当URubiconL央求时,会冒出二义性。

二义性德姆o目录结构

图片 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 第11中学就有了。

 从内容上来看,个性路由的剧情与守旧路由大致,形似有路由UPRADOL、路由值、调整器路由、路由约束和路由暗许值等。鉴于篇幅约束,在这里处就简单的概述一下,不作详细阐释,中期一时光依然有对象供给,再论述。

 定义:个性路由正是将路由U中华VL定义在调整器上或调节器内的格局上,而不像守旧路由将路由UCR-VL定义在RouteConfig.cs中。对比如下

图片 18

 

图片 19

3 路由生成U翼虎L

   路由三个主要任务:匹配传入的U奥迪Q3L诉求和布局与特定路由对应的U大切诺基L,回顾之相配U卡宴L和结构U陆风X8L。在生成U奥德赛L时,生成ULX570L的情趣应该率先与选择用来生成U普拉多L的路由相相称,那样路由就能够在管理传入或传播的U奥迪Q3L时成为完全的双向系统。原则上,开采职员应该提供生气勃勃组路由值,以便路由系统从当中选中第贰个能够相称U景逸SUVL的路由。

 3.1 UEvoqueL生成的高层系概述

  路由的主旨是叁个非常简单的算法,该算法基于叁个由RouteCollection类和RouteBase类组成的大约抽象对象。能够利用四种方式来生成U大切诺基L,但那些情势都以调用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方法遍历每种路由并访谈:“可以转换给定参数的U奇骏L吗”,这几个进度看似于在路由与传播央求相称时所接纳的特别逻辑。

(2)若是贰个路由能够应对上边的难点(即相称),那么它就能够再次回到一个包涵了UEscortL的VirTualPathData实例以致此外相称的新闻。不然,它就回去空值,路由体制移向列表中的下多个路由。

第1个重载选用四个参数,个中第一个参数是路由名称。在路由会集中路由名称是唯大器晚成的,也正是说,未有三个例外的路由具有相近的称号。当钦赐了路由名称时,路由群集就无需循环遍历各类路由,相反,它能够立即找到钦定名称的路由,并移向下边的步骤(2)。若是找到的路由无法合作钦命的参数,该措施就能够回去空值,况兼不再相配别的路由。

  3.2  UWranglerL生成详解

  (1)开荒职员调用像Html.ActionLink或Url.Action之类的不二等秘书技,这一个艺术反过来再调用RouteCollection.GetVirtual帕特h方法,并向它传递多个RequestContext对象、二个带有值的字典甚至用于选取生成U本田UR-VL的路由名称(可选参数)。

 (2)路由体制查看要求的路由参数(即未有提供路由参数的私下认可值),并保管提供的路由值字典为每二个渴求的参数提供一个值,不然,U奥迪Q7L生成程序就能够应声停下,并回到空值。

 (3)一些路由大概带有未有对应路由参数的暗中同意值。如路由或者为category键提供暗中认可值“pastries”,但是cateory不是路由U库罗德L的三个参数,这种景观下,假如客商传入的路由值字典为category提供了三个值,那么该值必须相配category的暗中认可值。

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

(5)路由极其成!以往能够通过查看每贰个路由参数,并尝试接受字典中的对应值填充相应参数,进而生成U奥迪Q3L。

能够包罗为如下流程图:

图片 20

 

4 路由绑定到操作

 在这里豆蔻年华章节,首要解析UPAJEROL绑定到调节器操作的尾部细节,剖判底层原理,理解ASP.NET央浼管道。注意,近期路由不止只是ASP.NET MVC的一个特征了,它曾经超(Jing Chao)过这些范围,如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中富含了关于相配哀告的路由音讯。

    如U奥迪Q5L:{Controller}/{action}/{id}。当乞求/albums/list/123传到时,该路由就可以尝试相称传入的乞请,假使合营成功,它就创办贰个字典,当中包含了从UTucsonL中剖判出的音信。确切地讲,路由还有大概会向Values字典中为UCR-VL中的各类路由参数增添多个键;对于古板路由{Controller}/{action}/{id},Values字典中应有最少含有多个键,分别是Controller,action和id,借使传入的U奇骏L是对/albums/list/123的伸手,路由就能够深入分析该央求的UEvoqueL,并为字典的键提供值。本例中,字典中“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,它就显得从(在地点栏中)当前倡议UMuranoL中领到的路由数据。如此,能够在地点栏中输入种种U本田CR-VL,并查看输入的U中华VL能与哪些路由分外,在页面尾巴部分,它还有只怕会显得一个分包应用程序定义的所用路由列表,那样能够查阅定义的哪个路由能够与当下U讴歌ZDXL相匹配。

设置教程如下:

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

图片 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】

【02】

【03】

【04】Professional Asp.net MVC 5

【05】

【06】

【07】

【08】

【09】

【10】

【11】

【12】

【13】

【14】

【15】

 

9   版权

 

  • 感激您的开卷,若有白璧微瑕,接待指教,共同学习、共同升高。
  • 博主网站:
  • 极少一些小说利用读书、参照他事他说加以考察、援用、抄袭、复制和粘贴等八种措施组成而成的,超越八分之四为原创。
  • 如您喜欢,麻烦推荐一下;如你有新主见,应接建议,邮箱:2014177728@qq.com。
  • 能够转发该博客,但必需盛名博客来源。

本文由永利皇宫官网发布于永利集团游戏网址,转载请注明出处:【ASP.NET MVC系列】浅谈ASP.NET MVC 路由

关键词: