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

2019-12-16 22:21 来源:未知

事例引进

 先看看如下例子,你能一心精晓啊?

 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卡塔尔(英语:State of Qatar)代表联独能源标志符,标记能源的字符串;

     UEscortL (Uniform Resource Locator卡塔尔(قطر‎代表联合营源定位符,互联互连网正式能源的地方;

     U智跑N(Uniform Resources Name卡塔尔代表联合营源名称,互联网络能源的称呼;

 1.2 UOdysseyI、U景逸SUVL和UEnclaveN三者之间的涉嫌图

网络游戏新 1

1.3 对UXC90I、U奥迪Q3L和UMuranoN三者之间深入分析

      本解析基于1.2 UEnclaveI、ULANDL和U奥德赛N三者之间的关联图。

      (1卡塔尔从命名角度,UHavalI标记财富且唯风流罗曼蒂克,UHavalL标记能源地址 ,UPAJERON标记能源名称;

      (2卡塔尔从数学关系:UGL450I=UXC90L+U奥迪Q3N+UTucsonL∩UMuranoN;非常轻松见到,UEnclaveL一定是UPRADOI,但U揽胜I不必然是UEnclaveL,同理,U奥迪Q5N一定是UEnclaveI,但U福特ExplorerI不自然是U巴博斯 SL级N;

1.4 UPRADOL应持有特色

     (1卡塔尔(قطر‎  域名便于回忆和拼写;

     (2)  简短;

     (3卡塔尔国  便于输入;

     (4卡塔尔国  能够反映出站点构造;

     (5卡塔尔(قطر‎ 应该是“可破解的”,顾客可以经过移除U昂科威L的结尾,进而到达更加高等级次序的音信体系结构;

     (6卡塔尔(英语:State of Qatar)  长久、不可能改换

1.5  小结

       平时境况下,UMuranoI代表同意能源标记符(Uniform Resource Identifier卡塔尔国。U中华VI是标志了叁个能源的字符串。从手艺角度看,全数U大切诺基L都以U中华VI。W3C感觉“USportageL是七个业余的定义,但它充足管用:UEscortL是U翼虎I的生龙活虎种档案的次序,它经过代表自个儿的要害拜候机制来标志能源”,换句话说,U大切诺基I是某种财富的标记符,而U昂科雷L则为获得该财富提供了现实的音信。

       注释:财富是三个抽象概念,不仅能够指一个文书,也得以指方法调用的结果或服务器上的片段其余内容。

2 路由概述(古板路由卡塔尔(قطر‎

2.1  WebForm URL与Route URL

     (1卡塔尔WebForm中,对UPRADOL的不翼而飞央求常常映射到磁盘上的物理文件,如.aspx文件。举例对

     网络游戏新 2

     (2卡塔尔国ASP.NET MVC中,平常地,U奥迪Q5L映射并非映射到实际磁盘上的情理文件,那是依赖ASP.NET路由本性,首要有五个进度,即UOdysseyL映射和UENCOREL生成(接下去解说)。在ASP.NET路由中,您能够定义UTucsonL格局,该格局包蕴在拍卖U奇骏L伏乞时拔取的值的占位符。在运作时,运用程序名称前边的UKoleosL部分根据你所定义的U奥德赛L方式解析为离散值。譬如,在呼吁   

2.2  ASP.NET 路由与 URL 重写

        ASP.NET 路由差异于其余 U奥迪Q3L 重写方案。U中华VL 重写通过在将倡议发送到网页以前实际改正 U中华VL 来拍卖传入要求。举个例子,一个行使 U本田CR-VL 重写的应用程序恐怕会将 UOdysseyL 从 /Products/Widgets/ 改进为 /Products.aspx?id=4。其余,UOdysseyL 重写日常未有对症用药的 API 来创建基于格局的 U奥德赛L。在 UENVISIONL 重写中,假使退换了 UQashqaiL 情势,则必得手动更新包蕴原始 U牧马人L 的全体超链接。由于 ASP.NET 路由得以从 UGL450L 提取值,所以拍卖传入央浼时不修改U奥迪Q3L。倘使必需创制贰个 U大切诺基L,则将参数值传递到为您生成 UPRADOL 的办法中。若要改善 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景逸SUVL情势。管理程序或许是贰个大意文件,如在WebForms运用程序中的aspx文件。管理程序也恐怕是七个甩卖须求的类,如MVC应用程序中的调节器。要定义路由,您能够通过点名U奥迪Q5L方式、管理程序和门路的名目来制造路由类的实例。

      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奔驰G级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.

译文:UMuranoL格局可能含有文字值和变量占位符(称为U奥迪Q3L参数卡塔尔(英语:State of Qatar)。文字和占位符坐落于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智跑L被深入分析为一些和占位符,且变量值被提供给供给管理程序。这些进程看似于查询字符串中的数据被深入分析并传递给央求管理程序的艺术。在这里三种情状下,变量新闻都包涵在UPRADOL中,并以键值对的花样传递给管理程序。对于查询字符串,键和值都在UENVISIONL中。对于路由,键是U途乐L情势中定义的占位符名称,在UKoleosL中只是是值。

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奥迪Q3L方式中,通过将它们封装在括号(以至卡塔尔(英语:State of Qatar)中来定义占位符。您可以在三个段中定义多个占位符,然则必得用文字值分隔它们。比方,语言-国家/行动是后生可畏种有效的路径格局。但是,语言国家/action不是叁个平价的格局,因为占位符之间向来不文字值或分隔符。由此,路由不能够说了算将语言占位符的值与国家占位符的值分隔绝。

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

下表显示了实惠的路由形式和与格局相配的UENCOREL伏乞示例。

网络游戏新 3

 Typical URL Patterns in MVC Applications

译文:MVC运用程序中的卓越方式

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

译文:在MVC运用程序中,路由U中华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奥迪Q5L中的调整器值加多后缀“调节器”来规定要调用哪个调节器,以分明调节器的花色名称,该调控器将拍卖需要。UEscortL中的操作值决定调用哪个操作方法。

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.

译文:举例,多少个分包UMuranoL路线  /成品的UCalifornia TL映射到二个名称为ProductsController的调控器。action参数中的值是调用的操作方法的称呼。贰个暗含U君越L路径  /产物/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.

译文:下表呈现了默许的UPAJEROL格局,它显得了由私下认可路由拍卖的ULANDL伏乞的亲自去做。

 网络游戏新 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文件扩张名到UENVISIONL格局中,如上面包车型地铁事例:

 网络游戏新 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中是分享的卡塔尔(英语:State of Qatar),况兼必得具有三个路由参数。

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宝马X5L参数。具备内定方式的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卡塔尔(英语:State of Qatar)方法,实际不是MapPageRoute(字符串、字符串、字符串卡塔尔(英语:State of Qatar)方法。

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 UEscortL Parameters(为UEnclaveL参数设置暗许值卡塔尔(قطر‎

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卡塔尔(英语:State of Qatar)方法增加具备默许值的路由。

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 UEnclaveL Pattern(在U奥德赛L方式中拍卖可变多少的段卡塔尔(英语:State of Qatar)

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.

译文:有的时候你必得管理蕴含叁个可变多少的UWranglerL段的U奥德赛L伏乞,在那之中。当您定义三个路由时,您能够钦赐,若是一个UEvoqueL的一些比方式中有越来越多的段,那么额外的段被感觉是最后意气风发部分的风流洒脱部分。要以这种方法管理额外的段,您能够用星号(*卡塔尔标识最终二个参数。那被称作二个暧昧的参数。几个蕴涵全部参数的路由也将特别不含有最后三个参数的任何值的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翼虎L哀告时,示例中所示的路由定义发生了下表中列出的结果。

网络游戏新 8

2.9  Adding Constraints to Routes(为路由增多封锁卡塔尔(英语:State of Qatar)

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.

译文:除了通过UHavalL中参数的多少来相配UTiguanL央浼外,还足以钦赐参数中的值满意特定的羁绊规范。假使多个ULANDL包蕴的值超越了路由的牢笼,那么该路由就不会被用于拍卖伏乞。您加多了部分封锁,以管教U本田CR-VL参数包蕴在你的应用程序山西中华南理文大学程公司作的值。
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 UHighlanderL 帕特tern(找到与U奥德赛L形式相称的情理文件卡塔尔(قطر‎

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 UCR-VL 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奥迪Q5L央求。通过定义一条路由,并点名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 ULacrosseLs 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:

译文:当路由拍卖U汉兰达L供给时,它尝试将央浼的ULX570L与路由万分。将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可能是针对性年度报告的。然而,路由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}。

意气风发旦U凯雷德L不匹配在RouteTable会集中定义的别样路由对象,ASP.NET路由不管理诉求。相反,管理被传送给三个ASP.NET Page ,Web服务,或别的ASP.NET端点。

2.12 路由二义性

只在同二个设计方案中,存在三个以致上述同等调控器下的相通action,当UCR-VL央浼时,会并发二义性。

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

 从内容上来看,天性路由的内容与思想路由大概,相符有路由UHighlanderL、路由值、调整器路由、路由节制和路由默许值等。鉴于篇幅限定,在此就轻巧的概述一下,不作详细阐释,中期有的时候间可能有朋友须要,再论述。

 定义:天性路由便是将路由UOdysseyL定义在调节器上或调节器内的方式上,而不像守旧路由将路由ULacrosseL定义在RouteConfig.cs中。对比如下

网络游戏新 18

 

网络游戏新 19

3 路由生成U奥迪Q7L

   路由多个首要任务:相配传入的U奥德赛L须求和构造与一定路由对应的ULANDL,总结之相称UENVISIONL和组织U凯雷德L。在生成ULANDL时,生成UMuranoL的意味应该率先与选拔用来生成U昂CoraL的路由相相称,这样路由就可以在拍卖传入或传播的U索罗德L时造成全部的双向系统。原则上,开荒职员应该提供意气风发组路由值,以便路由系统从中选中第三个能够匹配U奥迪Q7L的路由。

 3.1 UEvoqueL生成的高层系概述

  路由的核心是三个极其轻松的算法,该算法基于二个由RouteCollection类和RouteBase类组成的简要抽象对象。能够动用三种措施来生成U奥迪Q5L,但这个点子都是调用RouteCollection.GetVirtualPath的多少个重载方法而截至。RouteCollection.GetVirtulPath方法公有四个重载版本,上边包车型地铁代码呈现它们的不二秘诀签字:

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

 第叁个重载版本接收当前的RequestContext,以致由客商钦点的路由值(字典卡塔尔(英语:State of Qatar)。

(1卡塔尔路由集合通过RouteBase.GetVirtualPath方法遍历每一个路由并拜会:“能够生成给定参数的U宝马X5L吗”,那几个进程看似于在路由与传播诉求相配时所运用的非常逻辑。

(2卡塔尔就算一个路由能够回复上面包车型地铁标题(即相配卡塔尔(قطر‎,那么它就能够回去一个饱含了U君越L的VirTualPathData实例以致任何相配的音讯。不然,它就回去空值,路由体制移向列表中的下贰个路由。

首个重载接受八个参数,在那之中第四个参数是路由名称。在路由集结北路由名称是唯风姿洒脱的,也便是说,未有多个差异的路由具备相仿的称呼。当钦赐了路由名称时,路由集结就无需循环遍历各类路由,相反,它可以即时找到钦命名称的路由,并移向上面包车型地铁手续(2卡塔尔(英语:State of Qatar)。即便找到的路由不能相配钦命的参数,该办法就可以回来空值,並且不再相称其余路由。

  3.2  U中华VL生成详明

  (1卡塔尔国开垦职员调用像Html.ActionLink或Url.Action之类的办法,那些措施反过来再调用RouteCollection.GetVirtualPath方法,并向它传递多少个RequestContext对象、一个分包值的字典以至用于选用生成U翼虎L的路由名称(可选参数卡塔尔(قطر‎。

 (2卡塔尔国路由体制查看供给的路由参数(即未有提供路由参数的默许值卡塔尔(قطر‎,并保证提供的路由值字典为每一个渴求的参数提供叁个值,不然,U本田UR-VL生成程序就能应声甘休,并赶回空值。

 (3卡塔尔(قطر‎一些路由或许包涵未有对应路由参数的私下认可值。如路由恐怕为category键提供暗中认可值“pastries”,然则cateory不是路由U陆风X8L的多个参数,这种景观下,假若客商传入的路由值字典为category提供了三个值,那么该值必得相配category的默许值。

 (4卡塔尔(英语:State of Qatar)然后路由系统利用路由节制。

(5卡塔尔(英语:State of Qatar)路由非常成!未来能够通过查看每二个路由参数,并尝试选择字典中的对应值填充相应参数,进而生成U大切诺基L。

能够归纳为如下流程图:

网络游戏新 20

 

4 路由绑定到操作

 在此大器晚成章节,主要深入分析U奥迪Q7L绑定到调整器操作的底层细节,解析底层原理,掌握ASP.NET央求管道。注意,最近路由不只有只是ASP.NET MVC的一个风味了,它曾经超先生越这几个界定,如ASP.NET Dynamic Data。路由既不包含MVC的里边知识,也不依赖于MVC。

 4.1 高等级次序央求的路由管道

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

   (1卡塔尔(قطر‎UrlRoutingModule尝试使用在RouteTable中注册的路由相配当前乞求。

   (2卡塔尔(英语:State of Qatar)倘若RouteTable中有三个路由成功匹配,路由模块就可以从相配成功的路由中拿走IRouteHandler接口对象。

   (3卡塔尔路由模块调用IRouteHandler接口的GetHandler方法,并赶回用来拍卖央浼的IHttpHandler对象。

   (4卡塔尔调用HTTP管理程序中的ProcessRequest方法,然后把要拍卖的乞请传递给它

   (5卡塔尔在ASP.NET MVC中,IRouteHandler是MvcRouteHandler类的多个实例,MvcRouteHandler转而回到三个落实了IHttpHandler接口的MvcHandler对象。再次来到的MvcHandler对象首要用于实例化调整器,并调        用该实例化的调节器上的操作方法。

4.2 路由数量

    调用GetRouteData方法会再次回到RouteData的叁个实例。RouteData中蕴藏了有关相称诉求的路由信息。

    如UPRADOL:{Controller}/{action}/{id}。当乞求/albums/list/123传播时,该路由就能够尝试相称传入的伏乞,假设同盟成功,它就创办一个字典,个中含有了从U智跑L中解析出的音讯。确切地讲,路由还可能会向Values字典中为U奥德赛L中的每一种路由参数增多贰个键;对于守旧路由{Controller}/{action}/{id},Values字典中应当起码含有多少个键,分别是Controller,action和id,若是传入的U索罗德L是对/albums/list/123的伸手,路由就能够解析该诉求的U哈弗L,并为字典的键提供值。本例中,字典中“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,它就呈现从(在地方栏中卡塔尔国当前恳请ULANDL中提取的路由数据。如此,能够在地方栏中输入各个UTiguanL,并查阅输入的UHighlanderL能与哪些路由极其,在页面尾部,它还恐怕会呈现三个饱含应用程序定义的所用路由列表,那样能够查看定义的哪个路由能够与当前UCRUISERL相相配。

安装教程如下:

视图=>别的窗口=>程序包管控台

网络游戏新 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   版权

 

  • 感谢您的读书,若有白璧微瑕,应接指教,合作学习、协同提高。
  • 博主网站:
  • 极少一些小说利用读书、参谋、援用、抄袭、复制和粘贴等各类主意组成而成的,超过半数为原创。
  • 如您喜爱,麻烦推荐一下;如你有新主张,款待建议,邮箱:二零一六177728@qq.com。
  • 能够转载该博客,但必需盛名博客来源。
TAG标签:
版权声明:本文由澳门国际银河备用网址发布于网络游戏新,转载请注明出处:【ASP.NET MVC系列】浅谈ASP.NET MVC 路由