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

2019-10-15 10:43栏目:十大网赌网址
TAG:

事例引进

 先看看如下例子,你能完全明白啊?

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

     UOdysseyI(Uniform Resource Identifier)代表联合营源标志符,标志能源的字符串;

     U景逸SUVL (Uniform Resource Locator)代表联合营源定位符,互联英特网正式资源的地址;

     UMuranoN(Uniform Resources Name)代表联独财富名称,互联网络能源的名号;

 1.2 UGL450I、U福睿斯L和U昂CoraN三者之间的涉嫌图

图片 1

1.3 对U奔驰M级I、U索罗德L和U普拉多N三者之间分析

      本剖判基于1.2 U路虎极光I、U凯雷德L和UPAJERON三者之间的关联图。

      (1)从命名角度,UEnclaveI标记财富且独一,U大切诺基L标记能源地址 ,U帕杰罗N标志能源名称;

      (2)从数学关系:U传祺I=U奥迪Q5L+UMuranoN+U奥迪Q5L∩ULANDN;很轻易看到,ULANDL一定是U途乐I,但U奥迪Q5I不必然是URubiconL,同理,U奥迪Q3N一定是U大切诺基I,但UTiguanI不自然是U奥迪Q7N;

1.4 U安德拉L应负有特色

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

     (2)  简短;

     (3)  便于输入;

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

     (5)  应该是“可破解的”,客商能够通过移除U福特ExplorerL的末尾,进而达到更加高档期的顺序的信息种类布局;

     (6)  长久、无法改动

1.5  小结

       经常情形下,UENVISIONI代表同意财富标志符(Uniform Resource Identifier)。U路虎极光I是标志了叁个财富的字符串。从技巧角度看,全部U大切诺基L都以UOdysseyI。W3C以为“UENCOREL是一个非正式的概念,但它不行低价:U奇骏L是U宝马7系I的一种等级次序,它经过代表作者的第一会见机制来标记财富”,换句话说,U哈弗I是某种能源的标志符,而U本田CR-VL则为获取该财富提供了实际的信息。

       注释:财富是三个抽象概念,不仅能够指二个文件,也能够指方法调用的结果或服务器上的有的别样内容。

2 路由概述(古板路由)

2.1  WebForm URL与Route URL

     (1)WebForm中,对U奥德赛L的传播央浼经常映射到磁盘上的情理文件,如.aspx文件。举个例子对

     图片 2

     (2)ASP.NET MVC中,日常地,USportageL映射并不是映射到具体磁盘上的概略文件,那是依据ASP.NET路由脾气,紧要有多个进程,即UEnclaveL映射和UCR-VL生成(接下去讲授)。在ASP.NET路由中,您能够定义URubiconL模式,该格局包涵在拍卖UPRADOL央求时行使的值的占位符。在运营时,运用程序名称前面包车型地铁U科雷傲L部分依据你所定义的UCR-VL形式深入分析为离散值。举个例子,在乞求   

2.2  ASP.NET 路由与 URL 重写

        ASP.NET 路由区别于其他 U昂CoraL 重写方案。ULX570L 重写通过在将呼吁发送到网页此前实际改动 U奥迪Q5L 来拍卖传入央求。比方,两个应用 ULacrosseL 重写的应用程序或许会将 U途乐L 从 /Products/Widgets/ 退换为 /Products.aspx?id=4。别的,UTiggoL 重写经常未有对应的 API 来创立基于格局的 U牧马人L。在 UCRUISERL 重写中,假设改造了 U凯雷德L 方式,则必需手动更新饱含原始 U昂科雷L 的具备超链接。由于 ASP.NET 路由得以从 U奥迪Q5L 提取值,所以拍卖传入央浼时不改动U奥德赛L。假设非得成立二个 U奥迪Q5L,则将参数值传递到为你生成 UEvoqueL 的措施中。若要更换 UPRADOL 方式,请在某地方变动该情势,您在应用程序中开创的基于该模式的有所链接将自动使用新情势。

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蕴含了先行布置的UQX56L路由。那些都以在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迈凯伦570L情势只怕含有文字值和变量占位符(称为U奥迪Q5L参数)。文字和占位符位于USportageL的一部分中,由斜杠(/)字符分隔。

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.

译文:当发出诉求时,UQashqaiL被剖判为一些和占位符,且变量值被提要求诉求管理程序。那些进度看似于查询字符串中的数据被深入分析并传递给央求管理程序的办法。在这二种状态下,变量消息都包蕴在UCR-VL中,并以键值对的款型传递给处理程序。对于查询字符串,键和值都在UEnclaveL中。对于路由,键是UPAJEROL情势中定义的占位符名称,在ULX570L中仅仅是值。

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福特ExplorerL格局中,通过将它们封装在括号(以致)中来定义占位符。您能够在三个段中定义七个占位符,可是必得用文字值分隔它们。比如,语言-国家/行动是一种有效的路径情势。可是,语言国家/action不是八个可行的情势,因为占位符之间未有文字值或分隔符。因而,路由无法决定将语言占位符的值与国家占位符的值分隔绝。

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

下表显示了有效的路由形式和与情势匹配的UCRUISERL伏乞示例。

图片 3

 Typical URL Patterns in MVC Applications

译文:MVC运用程序中的优秀形式

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

译文:在MVC运用程序中,路由UTucsonL方式经常包含调整器和动作占位符。

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处理程序通过向UEvoqueL中的调整器值增添后缀“调整器”来鲜明要调用哪个调整器,以明确控制器的品类名称,该调节器将处理必要。U中华VL中的操作值决定调用哪个操作方法。

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.

译文:比如,三个富含UENVISIONL路线  /产品 的UKoleosL映射到三个名叫ProductsController的调整器。action参数中的值是调用的操作方法的称谓。三个含有UHighlanderL路线  /产品/show  的U凯雷德L会导致对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猎豹CS6L方式,它显得了由默许路由拍卖的USportageL诉求的躬体力行。

 图片 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和花色称号的U福睿斯L参数。具备钦定情势的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 U途达L Parameters(为UPorsche911L参数设置暗中认可值)

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.

译文:当您定义四个路由时,您可感到三个参数内定贰个暗中同意值。如若该参数的值未有包蕴在UWranglerL中,则选取暗许值。通过将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奥迪Q3L Pattern(在U中华VL情势中拍卖可变多少的段)

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.

译文:临时你必需管理包涵二个可变多少的UOdysseyL段的USportageL央浼,个中。当您定义二个路由时,您能够钦命,要是二个UENCOREL的部分比形式中有越来越多的段,那么额外的段被以为是终极一片段的一片段。要以这种方法管理额外的段,您能够用星号(*)标志最终一个参数。那被称作三个笼统的参数。三个包括全数参数的路由也将极其不分包最终一个参数的任何值的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路由拍卖叁个UKugaL诉求时,示例中所示的路由定义发生了下表中列出的结果。

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

译文:除了通过UPRADOL中参数的数目来相称UHighlanderL央浼外,还能钦命参数中的值知足一定的自律原则。固然叁个U奥迪Q7L包罗的值超越了路由的约束,那么该路由就不会被用来拍卖伏乞。您增加了一部分约束,以担保UOdysseyL参数富含在你的应用程序中专门的学问的值。
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 UEnclaveL Pattern(找到与UTiggoL格局相称的大要文件)

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奥迪Q5L Pattern(为U瑞鹰L情势显式禁止使用路由)

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 URAV4Ls 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与路由十分。将UPAJEROL诉求匹配到路由决计于以下原则:

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

若是U悍马H2L不兼容在RouteTable集合中定义的任何路由对象,ASP.NET路由不管理央浼。相反,管理被传送给一个ASP.NET Page ,Web服务,或另外ASP.NET端点。

2.12 路由二义性

只在同叁个施工方案中,存在多个乃至上述同等调整器下的同样action,当U奥迪Q5L央浼时,会出现二义性。

二义性德姆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中学就有了。

 从内容上来看,性格路由的剧情与价值观路由大约,同样有路由U路虎极光L、路由值、调控器路由、路由约束和路由暗许值等。鉴于篇幅限制,在这里边就轻松的概述一下,不作详细演说,前期一时间可能有意中人要求,再论述。

 定义:性格路由正是将路由UEscortL定义在调整器上或调整器内的主意上,而不像守旧路由将路由UHighlanderL定义在RouteConfig.cs中。相比方下

图片 18

 

图片 19

3 路由生成U奥迪Q5L

   路由七个首要职责:相配传入的UENCOREL哀告和组织与特定路由对应的UENVISIONL,总结之相称U大切诺基L和布局U路虎极光L。在生成UENVISIONL时,生成UEscortL的意思应该首先与选取用来生成U奥迪Q5L的路由相相配,那样路由就足以在管理传入或传播的U福特ExplorerL时改为完全的双向系统。原则上,开拓人员应该提供一组路由值,以便路由系统从当中选中第多个可以相称UGL450L的路由。

 3.1 U传祺L生成的高层系概述

  路由的中坚是叁个非常轻巧的算法,该算法基于八个由RouteCollection类和RouteBase类组成的总结抽象对象。能够选拔各类艺术来生成UEvoqueL,但这几个格局都是调用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本田UR-VL吗”,那个进程看似于在路由与传播必要相称时所运用的合作逻辑。

(2)假如贰个路由能够回复上边的标题(即相称),那么它就能够回去叁个含有了ULX570L的VirTualPathData实例乃至其余相配的新闻。不然,它就回来空值,路由体制移向列表中的下叁个路由。

其次个重载接受三个参数,在那之中第一个参数是路由名称。在路由集结中路由名称是当世无双的,也正是说,未有多个例外的路由具备同等的名号。当钦定了路由名称时,路由集结就不需求循环遍历各样路由,相反,它能够致时找到钦命名称的路由,并移向上边的步调(2)。假设找到的路由无法相称钦定的参数,该形式就能够回到空值,何况不再相配其余路由。

  3.2  U奥德赛L生成详解

  (1)开荒人士调用像Html.ActionLink或Url.Action之类的秘技,这么些情势反过来再调用RouteCollection.GetVirtualPath方法,并向它传递一个RequestContext对象、三个满含值的字典以至用于选用生成U昂CoraL的路由名称(可选参数)。

 (2)路由体制查看要求的路由参数(即未有提供路由参数的暗中同意值),并确定保障提供的路由值字典为每一种渴求的参数提供三个值,不然,UQX56L生成程序就能立时终止,并回到空值。

 (3)一些路由大概带有未有对应路由参数的暗中认可值。如路由大概为category键提供暗中认可值“pastries”,然则cateory不是路由UXC90L的多少个参数,这种场馆下,若是用户传入的路由值字典为category提供了多少个值,那么该值必需相配category的私下认可值。

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

(5)路由非常成!今后能够透过查看每多个路由参数,并尝试采取字典中的对应值填充相应参数,进而生成UEscortL。

能够包罗为如下流程图:

图片 20

 

4 路由绑定到操作

 在这里一章节,主要深入分析U昂CoraL绑定到调节器操作的平内部原因节,分析底层原理,通晓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中带有了有关相称伏乞的路由音讯。

    如UEvoqueL:{Controller}/{action}/{id}。当需要/albums/list/123传开时,该路由就能尝试相称传入的央求,假若相称成功,它就创制一个字典,此中含有了从UEnclaveL中解析出的消息。确切地讲,路由还可能会向Values字典中为U科雷傲L中的每一种路由参数加多三个键;对于价值观路由{Controller}/{action}/{id},Values字典中应有最少含有多个键,分别是Controller,action和id,假使传入的UPAJEROL是对/albums/list/123的乞请,路由就能深入分析该乞请的UCR-VL,并为字典的键提供值。本例中,字典中“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,它就显得从(在地点栏中)当前呼吁UENCOREL中领到的路由数据。如此,能够在地点栏中输入各个U奥迪Q7L,并查阅输入的UPRADOL能与哪些路由极其,在页面尾巴部分,它还只怕会来得八个含有应用程序定义的所用路由列表,那样能够查看定义的哪位路由能够与近日UXC60L相相配。

安装教程如下:

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

图片 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 路由