【ASP.NET MVC种类】浅谈ASP.NET MVC 路由

事例引进

§8 URLs and Routing

Before ASP.NET MVC, the core assumption of routing in ASP.NET (just like
in many other web application platforms) was that URLs correspond
directly to files on the server’s hard disk. The server executes and
serves the page or file corresponding to the incoming URL. Table 8–1
gives an example

葡萄娱乐场 1

这么, 限制会繁多, 有的人不想让旁人明白自身文件的路线,
大概是这一个代表方法太狼狈了等等.

 

 先看看如下例子,你能一心明了啊?

§8.1 Putting the Programmer Back in Control

ASP.NET MVC打破了这种规模, since ASP.NET MVC’s requests are handled by
controller classes (compiled into a .NET assembly), there are no
particular files corresponding to incoming
U景逸SUVLs.所以那也就未有渠道对应的特定文件了.

You are given complete control of your ULacrosseL schema—that is, the set of
U索罗德Ls that are accepted and their mappings to controllers and actions.
下边大家来探视mvc中是怎么定义路线的.

葡萄娱乐场 2

This is all managed by the framework’s routing
system.这全然是又框架的门径系统一管理理的.

 

§8.1.1 About Routing and Its .NET Assemblies

The routing system was originally designed for ASP.NET MVC, but it was
always intended to be shared with other ASP.NET technologies,
including Web Forms.路线系统本来是给mvc自身用的,
然则也会被别的asp.net才具使用.
所以路线代码是坐落三个单独的顺序集里(System.Web.Routing.dll in .NET
三.5, and simply System.Web.dll in .NET 4),而不是在System.Web.Mvc.dll
中.

 

 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 }

§8.2 Setting Up Routes

大家来探视路线的计划, 在global.asax.cs文件里

    public class MvcApplication : System.Web.HttpApplication
    {
        public static void RegisterRoutes(RouteCollection routes)
        {
            routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
            routes.MapRoute(
                "Default", // 路由名称
                "{controller}/{action}/{id}", // 带有参数的 URL
                new { controller = "Home", action = "Index", id = UrlParameter.Optional } // 参数默认值
            );
        }

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

When the application first starts up (i.e., when Application_Start()
runs), the RegisterRoutes() method populates a global static
RouteCollection object called RouteTable.Routes. That’s where the
application’s routing configuration lives. The most important code is
that shown in bold: MapRoute() adds an entry to the routing
configuration. To understand what it does a little more clearly, you
should know that this call to MapRoute() is just a concise alternative
to writing the following:当应用程序运营的时候,也正是Application_Start()
鱼腥的时候, RegisterRoutes()
静态方法会装入3个名称叫RouteTable.Routes的大局静态RouteCollection对象.
也是放置路线配置的地点.MapRoute是路径配置的入口, 为了轻巧的印证,
我们来举上边包车型地铁例子

            Route myRoute = new Route("{controller}/{action}/{id}", new MvcRouteHandler())
            {
                Defaults = new RouteValueDictionary(new
                {
                    controller = "Home",
                    action = "Index",
                    id = UrlParameter.Optional
                })
            };
            routes.Add("Default", myRoute);

俺们地点的看到的那段代码和连串自动生成的那段代码是平等的.

葡萄娱乐场 3

 

§8.2.1  Understanding the Routing Mechanism

The routing mechanism runs early in the framework’s request processing
pipeline. Its job is to take an incoming UCR-VL and use it to obtain an
IHttpHandler object that will handle the request.
早起的路由机制运作在框架的呼吁处理管道. 它的工作就是使用进来的UMuranoL,
并用它来得到贰个可见处理请求的的IHttpHandler 对象

Many newcomers to the MVC Framework struggle with routing. It isn’t
comparable to anything in earlier ASP.NET technologies, and it’s easy
to configure wrong. By understanding its inner workings, you’ll avoid
these difficulties, and you’ll also be able to extend the mechanism
powerfully to add extra behaviors across your whole
application.繁多mvc框架的菜鸟对路由的定义改到很质疑.
因为它和将来任何的asp.net技艺差别,而且很轻便配置错误.
通过打听它的在那之中运营,大家就足以幸免那么些题目,你也足以透过扩大额外的行事使整个应用程序拓展的更结实大.

The Main Characters: RouteBase, Route, and RouteCollection

路由配置首要有3个部分:

  • RouteBase is the abstract base class for a routing entry.
    You can implement unusual routing behaviors by deriving a custom
    type from it (I’ve included an example near the end of this
    chapter), but for now you can forget about it.
  • Route is the standard, commonly used subclass of RouteBase
    that brings in the notions of URL templating, defaults, and
    constraints. This is what you’ll see in most examples.
  • A RouteCollection is a complete routing configuration. It’s
    an ordered list of RouteBase-derived objects (e.g., Route
    objects).

How Routing Fits into the Request Processing Pipeline

When a UPRADOL is requested, the system invokes each of the IHttpModules
registered for the application. 当3个UTiggoL被呼吁,
系统调用每一种在应用程序中曾经注册的IHttpModules
.当中二个正是UrlRoutingModule

** 

The Order of Your Route Entries Is Important

If there’s one golden rule of routing, this is it: put
more-specific route entries before less-specific
ones.
若是有个路由安顿的金子规则: 那么正是将卓殊路线放在一般路径的前边.
因为系统的方便由的算法是从最上方开始, 而不是找最契合的.

 

§8.2.2  Adding a Route Entry

暗许的路由是很普通的, 倘诺你想要处理任何类其他U瑞虎L, 你还亟需做1些手脚.
作者来举个大致的事例, 比如大家想要用URAV四L /Catalog来查看这一个种类的享有产品

            routes.Add(new Route("Catalog", new MvcRouteHandler())
            {
                Defaults = new RouteValueDictionary(
                new { controller = "Products", action = "List" }
                )
            });

我们能够用地点的那段代码来贯彻大家的目的. 它能够帮助大家兑现/Catalog
也许是 /Catalog?some=querystring, 可是 /Catalog/Anythingelse
那样的url是丰富的.

 

URL Patterns Match the Path Portion of a URL

葡萄娱乐场 4

 

Meet RouteValueDictionary

A different technique to populate a RouteValueDictionary is to
supply an IDictionary<string, object> as a constructor
parameter, or alternatively to use a collection initializer, as in the
following example:

            routes.Add(new Route("Catalog", new MvcRouteHandler())
            {
                Defaults = new RouteValueDictionary
                {
                    { "controller", "Products" },
                    { "action", "List" }
                }
            });

 

Take a Shortcut with MapRoute()

ASP.NET MVC adds an extension method to RouteCollection, called
MapRoute(). 你会意识那比使用routes.Add(new Route(…)) 方便好些个.

            routes.MapRoute("PublicProductsList", "Catalog",
                new { controller = "Products", action = "List" });

In this case, PublicProductsList is the name of the route entry.
It’s just an arbitrary unique string. That’s optional.

 

§8.2.3  Using Parameters

As you’ve seen several times already, parameters can be accepted via a
curly brace syntax. 正像你前边看到的, 参数能够放在{}里,
那里大家加3个color参数到路由中:

            routes.MapRoute(null, "category/{color}",
               new { controller = "Products", action = "List" });

This route will now match URLs such as /Catalog/yellow or
/Catalog/1234, and the routing system will add a corresponding
name/value pair to the request’s RouteData object. On a request
to /Catalog/yellow, for example, RouteData.Values[“color”] would be
given the value yellow
.

 

Receiving Parameter Values in Action Methods

You know that action methods can take parameters. When ASP.NET MVC
wants to call one of your action methods, it needs to supply a value
for each method parameter. One of the places where it can get values
is the RouteData collection. It will look in RouteData’s Values
dictionary, aiming to find a key/value pair whose name matches the
parameter name.

咱俩知晓action方法能够带参数. 当mvc想要调用一个action方法,
它必要提供2个value给艺术的参数. 它拿走value的叁个地点正是RouteData
collection.
它会在RouteData’s
的键值对中查究3个和参数名对应的value.
So, if you have an action method like the following, its color
parameter would be populated according to the {color} segment parsed
from the incoming URL:

故此, 假诺你有个action方法像上面那样的,
那么它的color参数就在传诵的url中的{color}中

        public ActionResult List(string color)
        {
            // Do something
        }

To be more precise, action method parameters aren’t simply taken
directly from RouteData.Values, but instead are fetched via the
model binding system, which is capable of instantiating and
supplying objects of any .NET type, including arrays and collections.
You’ll learn more about this mechanism in Chapters 九 and 12.
更加纯粹的说,
action方法的参数不仅仅只是简短的向来从RouteData.Values获取.
而是从模型绑定系统中取得,各个.net类型. 你会在第10章和1二章中领悟越多.

 

§8.2.4  Using Defaults

You didn’t give a default value for {color}, so it became a mandatory
parameter. The Route entry no longer matches a request for /Catalog.
You can make the parameter optional by adding to your Defaults object:
在上头的例子中, 大家未有给{color}二个暗中认可值, 它成为了1个威胁的参数.
路由入口不再相称/Catalog 请求. 你能够

            routes.MapRoute(null, "Catalog/{color}",
                new { controller = "Products", action = "List", color = (string)null });

那样, 路由就能相配/Category和/Category/orange了.

倘使您想要一个非null 的默许值, 比如未有null的 int, 你能够显式的钦赐值

            routes.Add(new Route("Catalog/{color}", new MvcRouteHandler())
            {
                Defaults = new RouteValueDictionary(
                new { controller = "Products", action = "List", color = "Beige", page = 1 }
                )
            });

That’s a perfectly fine thing to do; it’s the correct way to set up
RouteData values that are actually fixed for a given Route
entry. For example, for this Route object,
RouteData[“controller”] will always equal “Products”, regardless
of the incoming URL, so matching requests will always be handled by
ProductsController.

那样,不管道输送入的url是怎么, 相配请求总会被ProductsController处理.

Remember that when you use MvcRouteHandler (as you do by default
in ASP.NET MVC), you must have a value called controller; otherwise,
the framework won’t know what to do with the incoming request and will
throw an error. The controller value can come from a curly brace
parameter in the URL, or can just be specified in the Defaults object,
but it cannot be omitted.

 

Creating Optional Parameters with No Default Value

就像私下认可的路由配置, 大家能够钦赐私下认可值UrlParameter.Optional.

            routes.MapRoute(null, "Catalog/{page}",
                new { controller = "Products", action = "List", page = UrlParameter.Optional });

如此, 当访问的UGL450L有page值的时候, 咱们就接纳传入的vallue, 假诺没有,
那么大家就不想action方法中传任何参数.你只怕会纳闷,
为何不用0可能是null 作为私下认可参数, 上边是它的三个原因:

  • If your action method takes a page parameter of type int, then
    because that type can’t hold null, you would have to supply the
    default value of 0 or some other int value. This means the action
    method would now always receive a legal value for page, so you
    wouldn’t be able to control the default value using the MVC
    Framework’s [DefaultValue] attribute or C# 4’s optional
    parameter syntax on the action method itself (you’ll learn more
    about these in the next chapter).
  • 若是你的action方法有个int类型的page参数,可是它是值类型,
    无法是null. 所以你需求提供三个暗中同意值(0也许是任何的值).
    那也感到着action方法总是须要二个合法的值, 所以,
    若是action方法本身行使mvc框架的[defaultvalue]特征或然是C#4的可选参数语法,
    你将不可能调控它的类型.(你会在接下去的1章中询问越多)
  • Even if your action’s page parameter was nullable, there’s a
    further limitation. When binding incoming data to action method
    parameters, the MVC Framework prioritizes routing parameter values
    above query string values (you’ll learn more about value providers
    and model binding in Chapter 12). So, any routing value for
    page—even if it’s null—would take priority and hide any query
    string value called page.
  • 即时您的action的page参数能够是null类型. 这里还有个限制.
    当action方法的参数是binding类型的时候, mvc
    框架会将路由参数优先于查询字符串值.(你会在1二章中学到值提供者和模型绑定).
    所以,
    任何为page设置的路由值–即便是null–也会预先于访问page的查询字符串

UrlParameter.Optional缓解了那五个难题

 

§8.2.5  Using Constraints

神跡, 你会想要加多额外的标准化, 以合营特定的route. 比如:

  • 您想相称get请求, 而不是post请求
  • 壹些参数要同盟特定的参数(e.g. ID参数必须同盟数字类型)
  • 局地route用来相称常规的web浏览器发来的请求,
    有的相称iphone发来的平等U昂科威L

In these cases, you’ll use the Route’s Constraints property

 

Matching Against Regular Expressions

为了确认保障参数是数字类型的, 大家使用那样的规则:

            routes.MapRoute(null, "Articles/{id}",
                new { controller = "Articles", action = "Show" },
                new { id = @"\d{1,6}" });

如此那般, route就会相配 /Articles/1 和 /Articles/12345陆 那两种类型,
而不是任何的,(这里的正则表达式表示的是: 数字类型,一~6个)

 

Matching HTTP Methods

If you want your Route to match only GET requests (not POST
requests), you can use the built-in HttpMethodConstraint class (it
implements IRouteConstraint)—for example:

            routes.MapRoute(null, "Articles/{id}", 
                new { controller = "Articles", action = "Show" },
                new { httpMethod = new HttpMethodConstraint("GET") });

您想相配什么样的HTTP方法, 就把它放到HttpMethodConstraint构造器中,
比如,new HttpMethodConstraint(“GET”, “DELETE”).

您要小心的是 HttpMethodConstraint[HttpGet] and
[HttpPost]
无关

 

Matching Custom Constraints

只要前边的三种都不能够满意你, 那么你仍是能够兑现它的.
举个例证,倘诺您想建立叁个只允许web浏览器进入的路由入口,
你能够创制如下的牢笼:

        public class UserAgentConstraint : IRouteConstraint
        {
            private string _requiredSubstring;
            public UserAgentConstraint(string requiredSubstring)
            {
                this._requiredSubstring = requiredSubstring;
            }
            public bool Match(HttpContextBase httpContext, Route route, string paramName,
            RouteValueDictionary values, RouteDirection routeDirection)
            {
                if (httpContext.Request.UserAgent == null)
                    return false;
                return httpContext.Request.UserAgent.Contains(_requiredSubstring);
            }
        }

上边包车型地铁路由只可以同盟由iphone发起的呼吁:

            routes.Add(new Route("Articles/{id}", new MvcRouteHandler()){
                Defaults = new RouteValueDictionary(new { controller = "Articles", action = "Show" }),
                Constraints = new RouteValueDictionary(
                    new { id = @"\d{1,6}", userAgent = new UserAgentConstraint("iPhone") }});

 

§8.2.6  Prioritizing Controllers by
Namespace

§8.2.7  Accepting a Variable-Length
List of Parameters

§8.2.8  Matching Files on the Server’s
Hard Disk

§8.2.9  Using IgnoreRoute to Bypass the Routing System

public static void RegisterRoutes(RouteCollection routes)
{
    routes.IgnoreRoute("{filename}.xyz");
    // Rest of routing config goes here
}

Here, {filename}.xyz is treated as a URL pattern just like in a normal
route entry, so in this example,
the routing system will now ignore any requests for /blah.xyz or
/foo.xyz?some=querystring. (Of course,
you must place this entry higher in the route table than any other
entry that would match and handle
those URLs.) You can also pass a constraints parameter if you want
tighter control over exactly which
URLs are ignored by routing.

那边{filename}.xyz 被看成多少个U大切诺基L模型, 就如1个平淡无奇的路由入口. 

注:该例子未有进入区域

1 URI、URL与URN

 1.1 URI、URL和URN定义 

     UOdysseyI(Uniform Resource
Identifier)代表联独财富标记符,标记能源的字符串;

     U途胜L (Uniform Resource
Locator)代表统一财富定位符,互连网上规范财富的地址;

     U瑞鹰N(Uniform Resources
Name)代表统1能源名称,互连网上财富的称谓;

 一.二 U索罗德I、UEscortL和U奇骏N叁者之间的涉及图

葡萄娱乐场 5

一.三 对URAV4I、U猎豹CS6L和UQX56N3者之间解析

      本解析基于一.二UCRUISERI、U昂科拉L和U凯雷德N叁者之间的关联图。

     
(一)从命名角度,UHighlanderI标志能源且唯1,UQashqaiL标记能源地址
,URAV四N标记资源名称;

     
(二)从数学关系:U大切诺基I=UHavalL+U奥迪Q5N+U凯雷德L∩UENVISIONN;很轻巧看到,UHighlanderL一定是UPAJEROI,但U福睿斯I不分明是U锐界L,同理,UHavalN一定是USportageI,但USportageI不必然是U奇骏N;

一.肆 UCR-VL应有所特色

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

     (2)  简短;

     (三)  便于输入;

     (四)  能够呈现出站点布局;

     (5)
 应该是“可破解的”,用户可以透过移除U陆风X八L的尾声,进而达到更加高层次的音讯类别布局;

     (陆)  持久、不能够更换

1.5  小结

     
 常常情形下,U途乐I代表同意财富标志符(Uniform Resource
Identifier)。U本田UR-VI是标记了3个能源的字符串。从才能角度看,全体UWranglerL都是UTucsonI。W3C认为“U奥迪Q7L是三个非正式的定义,但它不行政管理用:UEscortL是U翼虎I的1种档次,它经过代表小编的显要走访机制来标记财富”,换句话说,ULacrosseI是某种能源的标记符,而U卡宴L则为获得该财富提供了现实的新闻。

     
 注释:财富是贰个抽象概念,既能够指2个文书,也足以指方法调用的结果或服务器上的局部任何剧情。

二 路由概述(传统路由)

2.1  WebForm URL与Route URL

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

   
 葡萄娱乐场 6

     (二)ASP.NET
MVC中,平常地,UPRADOL映射并非映射到实际磁盘上的情理文件,这是依据ASP.NET路由本性,主要有三个经过,即U君越L映射和U揽胜L生成(接下去批注)。在ASP.NET路由中,您能够定义UTucsonL形式,该情势涵盖在处理UTucsonL请求时采纳的值的占位符。在运行时,运用程序名称前面包车型客车UXC90L部分依照你所定义的UPRADOL格局分析为离散值。例如,在央求http://server/application/Products/show/beverages时,路由分析器可以将值Products、show和beverages传递给请求的处理程序。相反,在一个不由URL路由管理的请求中,/Products/show/beverages片段将被解释为运用程序中的一个文件的路径。
  

2.2  ASP.NET 路由与 URL 重写

        ASP.NET 路由分裂于其余 U哈弗L
重写方案。URubiconL 重写通过在将请求发送到网页以前实际更动 UCR-VL
来处理传入请求。例如,3个运用 URubiconL 重写的应用程序大概会将 U福特ExplorerL 从 /Products/Widgets/ 更换为 /Products.aspx?id=4。别的,U凯雷德L 重写平时未有对应的 API
来创立基于格局的 U大切诺基L。在 UMuranoL 重写中,倘使更换了 ULANDL
情势,则必须手动更新包罗原始 UKoleosL 的具有超链接。由于
ASP.NET 路由得以从 U纳瓦拉L 提取值,所以拍卖传入请求时不更动UWranglerL。借使必须创立多少个 UCR-VL,则将参数值传递到为您生成 UBMWX三L
的法子中。若要改换 UOdysseyL
情势,请在某地方变动该格局,您在应用程序中创制的基于该情势的具备链接将活动使用新格局。

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奥迪Q五L方式。处理程序或许是多个大意文件,如在WebForms运用程序中的aspx文件。处理程序也大概是四个甩卖请求的类,如MVC应用程序中的调整器。要定义路由,您能够透过点名UCR-VL方式、处理程序和渠道的称号来创制路由类的实例。

      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包涵了优先安插的URubiconL路由。这一个都以在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方式或者蕴含文字值和变量占位符(称为UKugaL参数)。文字和占位符位于U陆风X8L的有的中,由斜杠(/)字符分隔。

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.

译文:当发出请求时,UBMWX三L被解析为部分和占位符,且变量值被提需要请求处理程序。那几个进度看似于查询字符串中的数据被分析并传递给请求处理程序的点子。在那两种状态下,变量音信都带有在UPRADOL中,并以键值对的款型传递给处理程序。对于查询字符串,键和值都在ULANDL中。对于路由,键是U凯雷德L情势中定义的占位符名称,在U汉兰达L中唯有是值。

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.

译文:在UPRADOL情势中,通过将它们封装在括号(以及)中来定义占位符。您能够在三个段中定义多个占位符,不过必须用文字值分隔它们。例如,语言-国家/行动是壹种有效的门道方式。可是,语言国家/action不是三个可行的形式,因为占位符之间从未文字值或分隔符。因而,路由不可能操纵将语言占位符的值与国家占位符的值分隔绝。

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

下表呈现了卓有成效的路由情势和与情势相配的U奥迪Q5L请求示例。

葡萄娱乐场 7

 Typical URL Patterns in MVC
Applications

译文:MVC运用程序中的精湛格局

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

译文:在MVC运用程序中,路由U奥迪Q伍L方式常常包涵调整器和动作占位符。

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处理程序通过向ULX570L中的调控器值增多后缀“调节器”来显著要调用哪个调节器,以鲜明调节器的花色名称,该调节器将处理请求。URAV四L中的操作值决定调用哪个操作方法。

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.

译文:例如,二个分包UPAJEROL路线  /产品
的U普拉多L映射到二个名称叫ProductsController的调节器。action参数中的值是调用的操作方法的名称。贰个暗含U奥迪Q5L路径  /产品/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福睿斯L情势,它展现了由暗许路由拍卖的UCRUISERL请求的以身作则。

 葡萄娱乐场 8

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
柒.0,不需求任何文件名称扩张。对于IIS
六.0,您必须增添.mvc文件扩充名到U本田UR-VL情势中,如上边包车型地铁例子:

 葡萄娱乐场 9

 如在VS20一3选用MVC模板创立项目时,自动生成类RouteConfig.

葡萄娱乐场 10

贰.伍 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文件中,您能够在3个叫做Application_Start
方法里增多路由。该方法确定保障当应用程序运行时,路由是能够运用的。它还使您能够在对应用程序实行单元测试时一直调用该措施。假如你想在对应用程序进行单元测试时一向调用方法,那么注册路由的章程必须是静态的(在Visual
Basic中是共享的),并且必须有所3个路由参数。

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

二.七 Setting Default Values for U宝马7系L
Parameters(为UPRADOL参数设置暗中同意值)

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.

译文:当你定义3个路由时,您可认为三个参数钦点一个暗许值。假诺该参数的值未有包括在USportageL中,则选拔私下认可值。通过将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.

葡萄娱乐场 11

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

二.8 Handling a Variable Number of Segments
in a U奥迪Q3L Pattern(在U奥迪Q5L方式中拍卖可变多少的段)

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个可变多少的U驭胜L段的U哈弗L请求,其中。当您定义3个路由时,您能够钦点,倘使一个UHighlanderL的片段比情势中有越多的段,那么额外的段被认为是最终1有个别的一有个别。要以那种措施处理额外的段,您能够用星号(*)标识最终3个参数。那被号称三个暧昧的参数。三个分包全体参数的路由也将卓殊不分包最终2个参数的任何值的url。上边包车型大巴演示展现了1个相配未知数量的段的路由方式。

/ 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路由拍卖一个UavancierL请求时,示例中所示的路由定义发生了下表中列出的结果。

葡萄娱乐场 12

2.玖  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宝马X5L中参数的数额来相配U奥迪Q5L请求外,还是能钦点参数中的值满意一定的束缚原则。假诺三个U冠道L包罗的值大于了路由的羁绊,那么该路由就不会被用来拍卖请求。您增加了一些羁绊,以担保U奥迪Q三L参数包涵在您的应用程序中劳作的值。
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.

译文:假如你提供二个字符串,那么路由将字符串作为3个正则表明式来处理,并经过调用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.

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

葡萄娱乐场 13

 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 U凯雷德L Pattern(找到与U奥迪Q5L形式相称的物理文件)

By default, routing does not handle
requests that map to an existing physical file on the Web server. For
example, a request for
http://server/application/Products/Beverages/Coffee.aspx is not handled
by routing if a physical file exists at Products/Beverages/Coffee.aspx.
Routing does not handle the request even if it matches a defined
pattern, such as {controller}/{action}/{id}.

译文:暗许情状下,路由不处理映射到Web服务器上幸存物理文件的伸手。例如,借使存在 Products/Beverages/Coffee.aspx.物理文件,请求http://server/application/Products/Beverages/Coffee.aspx
不被路由拍卖。尽管它与已定义的格局相相配,路由不处理请求,例如调整器/动作/id。
If you want routing to handle all
requests, even requests that point to files, you can override the
default behavior by setting the RouteExistingFiles property of the
RouteCollection object to true. When you set this value to true, all
requests that match a defined pattern are handled by routing.

译文:假使你想要路由拍卖全部请求,甚至指向文件的伏乞,您能够经过安装RouteCollection对象的性情RouteExistingFiles为true, 
以此来覆盖暗中认可值。当您将以此值设置为true时,相称定义格局的有所请求都由路由拍卖。

Routing Is Explicitly Disabled for a
UPAJEROL Pattern(为UTiggoL格局显式禁用路由)

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 }

二.1一 How UMuranoLs 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请求时,它尝试将呼吁的USportageL与路由特出。将UTiggoL请求相称到路由取决于以下原则:

  • The route patterns that you have
    defined or the default route patterns, if any, that are included in
    your project type. 

  • 译文:您已经定义的路由形式或私下认可的路由情势,借使有的话,它们含有在您的连串连串中。

  • The order in which you added them to
    the Routes collection.
  •  译文:您将它们增加到路由集合的相继。

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

  • 译文:您为有些路由提供的别样私下认可值。
  • Any constraints that you have
    provided for a route.

  • 译文:您为路线所提供的其余约束。

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

  • 译文:是还是不是定义了路由来处理与物理文件匹配的呼吁。

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

译文:例如,倘若您增添了以下情势:
   Route 1 is set to
{controller}/{action}/{id}

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

 
译文:路线2设置为 products/show/{id}
Route 2 will never handle a request
because Route 1 is evaluated first, and it will always match requests
that could also work for Route 2. A request for
http://server/application/products/show/bikes seems to match Route 2
more closely, but it is handled by Route 1 with the following
values:
controller is products.
action is show.
id is bikes.

译文:

路由二长久不会处理请求,因为路由1第1被相配,它总是相配只怕在二号路线上干活的央浼。请求http://server/application/products/show/bikes似乎比赛路线2更紧密,但它是由路线1以下值:

控制器products.

行动是show.

id是bikes.

Default values are used if a parameter is
missing from the request. Therefore, they can cause a route to match a
request that you did not expect. For example, suppose that you add
routes with the following patterns:
Route 1: {report}/{year}/{month}, with
default values for year and month.
Route 2: {report}/{year}, with a default
value for year.
Route 2 will never handle a request.
Route 1 might be intended for a monthly report, and Route 2 might be
intended for an annual report. However, the default values in Route 1
mean that it will match any request that could also work for Route
2.

译文:

借使请求中缺点和失误二个参数,则使用默许值。因而,它们得以产生一条相称您未有预料到的哀求的路由。例如,假使您加多了以下情势:

路径1:报告/年/月,年和月暗中同意值。

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

路由2永恒不会处理请求。第一条恐怕是本着每月报告的,而路由贰只怕是针对性年度报告的。不过,路由1中的暗中同意值意味着它将相配任何大概用于路由贰的请求。

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端点。

二.1二 路由贰义性

只在同三个消除方案中,存在七个以及上述同等调控器下的一样action,当U安德拉L请求时,会油可是生2义性。

二义性Demo目录结构

葡萄娱乐场 14

RouteConfig.cs

葡萄娱乐场 15葡萄娱乐场 16

 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

葡萄娱乐场 17葡萄娱乐场 18

 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

葡萄娱乐场 19葡萄娱乐场 20

 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

测试结果

葡萄娱乐场 21

叁 路由概述(个性路由)

 性情路由是在ASP.NET MVC
5中新扩充的,守旧路由ASP.NET MVC 第11中学就有了。

 从内容上来看,本性路由的始末与价值观路由大概,一样有路由UPAJEROL、路由值、调整器路由、路由约束和路由暗中同意值等。鉴于篇幅限制,在那边就总结的概述一下,不作详细解说,中期有时间依然有意中人必要,再论述。

 定义:天性路由就是将路由U本田CR-VL定义在调控器上或调整器内的章程上,而不像古板路由将路由U牧马人L定义在RouteConfig.cs中。相比较如下

葡萄娱乐场 22

 

葡萄娱乐场 23

3 路由生成U奥迪Q7L

 
 路由五个重要任务:相配传入的ULANDL请求和结构与特定路由对应的U中华VL,归纳之相称USportageL和组织U哈弗L。在生成UHighlanderL时,生成UQashqaiL的乐趣应该首先与选拔用来生成U汉兰达L的路由相匹配,这样路由就足以在处理传入或传播的UPAJEROL时产生完全的双向系统。原则上,开辟职员应该提供一组路由值,以便路由系统从中选中第1个能够相配U福睿斯L的路由。

 叁.壹 U本田CR-VL生成的高层系概述

 
路由的为主是二个相当轻易的算法,该算法基于1个由RouteCollection类和RouteBase类组成的简便抽象对象。能够运用两种艺术来生成U昂CoraL,但那些办法都是调用RouteCollection.GetVirtualPath的1个重载方法而停止。RouteCollection.GetVirtulPath方法公有四个重载版本,上面包车型客车代码浮现它们的办法签字:

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

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

(一)路由集合通过RouteBase.GetVirtualPath方法遍历各类路由并走访:“能够生成给定参数的U宝马X三L吗”,这么些进程看似于在路由与传播请求匹配时所选用的合作逻辑。

(贰)就算多个路由能够回答上边的标题(即相称),那么它就会回来1个分包了U猎豹CS陆L的VirTualPathData实例以及别的相配的消息。不然,它就回去空值,路由体制移向列表中的下叁个路由。

其次个重载接受多少个参数,在那之中第三个参数是路由名称。在路由集合中路由名称是绝无仅有的,约等于说,没有八个不等的路由具有同等的名号。当钦赐了路由名称时,路由集合就不需求循环遍历各种路由,相反,它能够登时找到钦点名称的路由,并移向下边的步调(二)。假设找到的路由不能相称钦命的参数,该措施就会回到空值,并且不再匹配别的路由。

  三.二  UEnclaveL生成详解

 
(一)开辟职员调用像Html.ActionLink或Url.Action之类的办法,那么些艺术反过来再调用RouteCollection.GetVirtualPath方法,并向它传递七个RequestContext对象、三个饱含值的字典以及用于采纳生成UGL450L的路由名称(可选参数)。

 (②)路由体制查看供给的路由参数(即未有提供路由参数的暗许值),并保管提供的路由值字典为每3个渴求的参数提供三个值,不然,U奇骏L生成程序就会应声停下,并回到空值。

 (3)1些路由恐怕带有未有对应路由参数的暗许值。如路由大概为category键提供私下认可值“pastries”,不过cateory不是路由UHavalL的八个参数,那种气象下,假如用户传入的路由值字典为category提供了贰个值,那么该值必须相称category的暗中认可值。

 (肆)然后路由系统采纳路由约束。

(五)路由相当成!未来能够透过查阅每贰个路由参数,并尝试采用字典中的对应值填充相应参数,进而生成U汉兰达L。

能够包含为如下流程图:

葡萄娱乐场 24

 

肆 路由绑定到操作

 在这一章节,首要分析UHighlanderL绑定到调控器操作的最底层细节,分析底层原理,了解ASP.NET请求管道。注意,近期路由不仅仅只是ASP.NET
MVC的三个本性了,它已经超(Jing Chao)过那一个限制,如ASP.NET Dynamic
Data。路由既不包罗MVC的里边知识,也不借助于于MVC。

 四.一 高层次请求的路由管道

  当ASP.NET
拍卖请求时,路由管道重要由以下几步组成:

 
 (一)UrlRoutingModule尝试使用在RouteTable中登记的路由相配当前乞请。

 
 (二)即使RouteTable中有三个路由成功相称,路由模块就会从相称成功的路由中得到IRouteHandler接口对象。

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

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

   (五)在ASP.NET
MVC中,IRouteHandler是MvcRouteHandler类的四个实例,MvcRouteHandler转而回到三个落到实处了IHttpHandler接口的MvcHandler对象。重回的MvcHandler对象主要用来实例化调节器,并调
       用该实例化的调整器上的操作方法。

四.二 路由数量

   
调用GetRouteData方法会再次来到RouteData的2个实例。RouteData中蕴藏了有关相配请求的路由音信。

   
如U君越L:{Controller}/{action}/{id}。当请求/albums/list/1②三传唱时,该路由就会尝试相配传入的乞求,固然相配成功,它就成立一个字典,其中饱含了从U昂科威L中分析出的音讯。确切地讲,路由还会向Values字典中为U奥德赛L中的每一种路由参数增加二个键;对于价值观路由{Controller}/{action}/{id},Values字典中应当至少含有多个键,分别是Controller,action和id,要是传入的U中华VL是对/albums/list/1二叁的呼吁,路由就会分析该请求的UKugaL,并为字典的键提供值。本例中,字典中“Controller”键的值为albums,”action”键的值为“list”,”id”键的值是“1二三”;对于天性路由MVC使用DataTokens字典来囤积更可信赖的音讯,而不是操作名称字符串。具体来讲,它富含3个操作描述符列表,那几个描述符间接指向路由相配时恐怕行使的操作方法。对于调控器品级的特色路由,列表大校有不止三个操作。在总体MVC中都有利用的RequestContext的RouteData属性保存着外面路由值。

伍 路由调试

 
 使用RouteDebugger调节和测试,启用RouteDebugger后,它会用3个DebuggerRouteHandler替换全部路由处理程序,DebugRouteHandler截获全体传入的伏乞,并查询路由表中的每贰个路由,以便在页面尾巴部分展现路由的确诊数据和参数。为利用RouteDebugger,只需在VS的Package
Manager Console窗口中选拔NuGet安装就可以,命令Install-Package
routedebugger.。RouteDebugger包在增添Route
Debugger程序集的还要。也在web.config文件的appSettings节点中增多二个安装,用来拉开或禁用路由调节和测试。

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

 只要启用RouteDebugger,它就显示从(在地方栏中)当前央浼ULacrosseL中领取的路由数据。如此,能够在地方栏中输入各类URubiconL,并查看输入的U昂科雷L能与哪些路由特出,在页面尾部,它还会呈现一个带有应用程序定义的所用路由列表,那样能够查阅定义的哪些路由能够与当前U卡宴L相相配。

设置教程如下:

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

葡萄娱乐场 25

在窗口中输入:Install-Package
routedebugger

葡萄娱乐场 26

抑或也得以动用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>

 

葡萄娱乐场 27

陆 与路由相关的根本命名空间和类

 陆.一  路由涉及的命名空间

葡萄娱乐场 28

 陆.贰 Class
Reference( 路由涉及到的重中之重类)

葡萄娱乐场 29

 

7 总结

 由于篇幅有限,路由章节就写到那,当然,还有不少剧情没写,如路由安排文件、路由平安设置、自定义路由约束等,留给读者对象们去斟酌吗。

8 参考文献

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

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

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

【04】Professional Asp.net MVC 5

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

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

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

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

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

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

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

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

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

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

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

 

9   版权

 

  • 多谢您的读书,若有不足之处,欢迎指教,共同学习、共同进步。
  • 博主网站:http://www.cnblogs.com/wangjiming/。
  • 极少1些文章利用读书、参考、引用、抄袭、复制和粘贴等各类方法结合而成的,超越二伍%为原创。
  • 如你喜欢,麻烦推荐一下;如你有新想法,欢迎提议,邮箱:二〇一五17772八@qq.com。
  • 能够转发该博客,但必须盛名博客来源。