Identifier)代表统一能源标志符,有的人不想让人家知道本人文件的门道

事例引入

§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福睿斯Ls.所以那也就从不路子对应的特定文件了.

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 四),而不是在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()
静态方法会装入一个誉为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 U路虎极光L and use it to obtain an
IHttpHandler object that will handle the request.
早起的路由机制运转在框架的伏乞管理管道. 它的做事正是应用进来的U揽胜极光L,
并用它来获得一个可见处理请求的的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 U冠道L is requested, the system invokes each of the IHttpModules
registered for the application. 当三个U卡宴L被呼吁,
系统调用种种在应用程序中早就注册的IHttpModules
.在那之中3个就是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, 你还亟需做一些手脚.
笔者来举个简单的事例, 举个例子我们想要用U奥迪Q7L /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. 正像你面前看到的, 参数能够放在{}里,
那里大家加一个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想要调用1个action方法,
它供给提供1个value给艺术的参数. 它拿走value的多少个地点正是RouteData
collection.
它会在RouteData’s
的键值对中搜索一个和参数名对应的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 1贰.
更加准确的说,
action方法的参数不仅仅只是轻巧的一贯从RouteData.Values获取.
而是从模型绑定系统中获取,各样.net类型. 你会在第十章和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个暗中认可值, 它产生了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 });

如此, 当访问的UKoleosL有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).
  • 1经你的action方法有个int类型的page参数,不过它是值类型,
    不可能是null. 所以你须求提供四个暗中认可值(0恐怕是其他的值).
    那也以为着action方法总是须要多少个合法的值, 所以,
    假使action方法本身行使mvc框架的[defaultvalue]特色可能是C#4的可选参数语法,
    你将不也许调节它的类型.(你会在接下去的一章中打听越来越多)
  • 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/一 和 /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奥迪Q5L模型, 就如多少个惯常的路由入口. 

注:该例子未有参预区域

1 URI、URL与URN

 1.1 URI、URL和URN定义 

     U大切诺基I(Uniform Resource
Identifier)代表联独能源标志符,标志能源的字符串;

     ULacrosseL (Uniform Resource
Locator)代表统一能源定位符,互联英特网标准能源的地方;

     U奥迪Q三N(Uniform Resources
Name)代表统1财富名称,互连网络财富的名目;

 一.二 UCRUISERI、UQX56L和U奔驰M级N叁者之间的关联图

图片 5

一.叁 对U中华VI、U牧马人L和U奥德赛N3者之间解析

      本解析基于一.2U卡宴I、UHavalL和U纳瓦拉N3者之间的涉嫌图。

     
(1)从命名角度,U凯雷德I标记财富且唯壹,U哈弗L标记能源地址
,UTucsonN标志财富名称;

     
(2)从数学关系:U悍马H二I=UKugaL+U奇骏N+U福特ExplorerL∩U锐界N;很轻巧看到,UWranglerL一定是UEnclaveI,但UEnclaveI不必然是URubiconL,同理,U凯雷德N一定是U卡宴I,但UENVISIONI不自然是ULX570N;

壹.四 UCRUISERL应享有特色

     (壹)  域名便于记念和拼写;

     (2)  简短;

     (三)  便于输入;

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

     (伍)
 应该是“可破解的”,用户能够经过移除USportageL的最终,进而达到越来越高档案的次序的新闻体系布局;

     (六)  持久、无法改动

1.5  小结

     
 日常情状下,UPAJEROI代表同意能源标记符(Uniform Resource
Identifier)。URAV4I是标记了三个能源的字符串。从技能角度看,全体U牧马人L都以ULacrosseI。W3C以为“U讴歌MDXL是3个非正式的定义,但它不行政管理用:ULacrosseL是U昂科威I的壹种档案的次序,它经过代表笔者的重中之重走访机制来标记能源”,换句话说,UEnclaveI是某种财富的标记符,而ULacrosseL则为获得该财富提供了具体的消息。

     
 注释:财富是一个抽象概念,既可以指3个文件,也得以指方法调用的结果或服务器上的有个别别的剧情。

2 路由概述(守旧路由)

2.1  WebForm URL与Route URL

   
 (一)WebForm中,对U路虎极光L的流传请求常常映射到磁盘上的情理文件,如.aspx文件。比方对http://server/application/Product.aspx?id=4的请求映射到名为Products.aspx文件,该文件包含代码和标记用于呈现对浏览器的响应,一般请求示过程抽象如下:

   
 图片 6

     (2)ASP.NET
MVC中,常常地,U本田CR-VL映射并非映射到实际磁盘上的情理文件,那是依据ASP.NET路由特性,重要有五个进度,即U奇骏L映射和UKoleosL生成(接下去解说)。在ASP.NET路由中,您可以定义UBMWX三L方式,该形式涵盖在管理UXC60L请求时选用的值的占位符。在运作时,运用程序名称前边的U帕杰罗L部分依照你所定义的U大切诺基L情势分析为离散值。举例,在呼吁http://server/application/Products/show/beverages时,路由分析器可以将值Products、show和beverages传递给请求的处理程序。相反,在一个不由URL路由管理的请求中,/Products/show/beverages片段将被解释为运用程序中的一个文件的路径。
  

2.2  ASP.NET 路由与 URL 重写

        ASP.NET 路由差别于其余 U宝马X叁L
重写方案。U帕杰罗L 重写通过在将呼吁发送到网页在此之前实际更动 U奥迪Q7L
来管理传入请求。举个例子,1个利用 UENVISIONL 重写的应用程序恐怕会将 U奇骏L 从 /Products/Widgets/ 改造为 /Products.aspx?id=四。其余,UQX56L 重写经常未有对号入座的 API
来制造基于情势的 U本田CR-VL。在 U福睿斯L 重写中,即便改变了 U兰德酷路泽L
格局,则必须手动更新蕴涵原始 U奥迪Q7L 的保有超链接。由于
ASP.NET 路由得以从 UHavalL 提取值,所以拍卖传入请求时不变U卡宴L。借使必须创建三个 UWranglerL,则将参数值传递到为您生成 UEscortL
的诀窍中。若要改变 U路虎极光L
情势,请在某地点变动该情势,您在应用程序中开创的基于该情势的有所链接将自行使用新形式。

二.三  路由定义

        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应用程序中的调节器。要定义路由,您能够经过点名USportageL形式、管理程序和路线的名号来创立路由类的实例。

      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包含了优先安排的UTiguanL路由。那个都以在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.

译文:URubiconL格局可能包罗文字值和变量占位符(称为UCRUISERL参数)。文字和占位符位于UEscortL的一部分中,由斜杠(/)字符分隔。

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被解析为部分和占位符,且变量值被提须要请求管理程序。这一个进度看似于查询字符串中的数据被解析并传递给请求管理程序的主意。在那二种情况下,变量音讯都含有在U奥德赛L中,并以键值对的花样传递给处理程序。对于查询字符串,键和值都在U本田UR-VL中。对于路由,键是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.

译文:在U卡宴L方式中,通过将它们封装在括号(以及)中来定义占位符。您能够在2个段中定义几个占位符,不过必须用文字值分隔它们。比方,语言-国家/行动是1种有效的门径形式。然则,语言国家/action不是2个得力的情势,因为占位符之间平昔不文字值或分隔符。由此,路由不可能调节将语言占位符的值与国家占位符的值分隔开分离。

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

下表展现了实用的路由情势和与形式相配的U揽胜L请求示例。

图片 7

 Typical URL Patterns in MVC
Applications

译文:MVC运用程序中的特出情势

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

译文:在MVC运用程序中,路由U猎豹CS6L情势平常蕴含调节器和动作占位符。

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牧马人L中的调整器值增添后缀“调整器”来规定要调用哪个调节器,以分明调节器的项目名称,该调整器将拍卖请求。UPAJEROL中的操作值决定调用哪个操作方法。

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.

译文:比方,贰个饱含UEvoqueL路线  /产品
的URL映射到二个名字为ProductsController的调节器。action参数中的值是调用的操作方法的称号。三个富含U哈弗L路径  /产品/show
 的U宝马X3L会促成对ProductsController类的Showmethod的调用。

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

译文:下表展现了默许的USportageL情势,它显得了由暗中认可路由拍卖的UQashqaiL请求的示范。

 图片 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
7.0,不须求别的文件名称扩张。对于IIS
陆.0,您必须增多.mvc文件扩大名到UXC90L格局中,如下边包车型大巴例证:

 图片 9

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

图片 10

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方法创设2个路由对象并将其增多到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中是共享的),并且必须怀有1个路由参数。

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 UCR-VL
Parameters(为U卡宴L参数设置默许值)

When you define a route, you can assign a
default value for a parameter. The default value is used if a value for
that parameter is not included in the URL. You set default values for a
route by assigning a dictionary object to the Defaults property of the
Route class. The following example shows how to add a route that has
default values, by using the MapPageRoute(String, String, String,
Boolean, RouteValueDictionary) method.

译文:当您定义三个路由时,您可感到八个参数钦赐多个默许值。假设该参数的值未有包含在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 UXC90L 帕特tern(在UWranglerL方式中拍卖可变多少的段)

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.

译文:有时你必须管理包括三个可变多少的UXC60L段的U奥德赛L请求,个中。当你定义二个路由时,您能够内定,假如3个ULANDL的有个别比形式中有越多的段,那么额外的段被以为是最后壹部分的1部分。要以这种办法处理额外的段,您能够用星号(*)标识最终八个参数。那被称作二个暧昧的参数。2个饱含全部参数的路由也将合作不包括最终二个参数的任何值的url。上面包车型大巴以身作则呈现了三个卓越未知数量的段的路由情势。

/ query / { queryname } { * queryvalues
}

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

译文:当ASP.NET路由拍卖三个U福特ExplorerL请求时,示例中所示的路由定义发生了下表中列出的结果。

图片 12

二.玖  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.

译文:除了通过ULX570L中参数的数据来相称U昂CoraL请求外,还是能钦定参数中的值满意一定的自律原则。如若二个U福特ExplorerL包蕴的值抢先了路由的约束,那么该路由就不会被用来拍卖请求。您增加了某些羁绊,以有限援助U凯雷德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.

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

图片 13

 2.拾 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
路由也不管理请求。本有的讲述了1部分气象,当中路由不管理请求。

A Physical File is Found that Matches
the ULacrosseL Pattern(找到与U悍马H二L方式相称的情理文件)

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
UCRUISERL 帕特tern(为U奥迪Q5L情势显式禁止使用路由)

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  

译文:您还是能够钦点路由不该管理有个别UPAJEROL请求。通过定义一条路由,并点名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 U安德拉Ls 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请求时,它尝试将呼吁的U大切诺基L与路由非常。将U福特ExplorerL请求相称到路由取决于以下原则:

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

译文:

路由2永恒不会处理请求,因为路由壹先是被相配,它连接相配恐怕在二号路线上干活的伸手。请求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条可能是针对性每月报告的,而路由2大概是指向年度报告的。然而,路由第11中学的私下认可值意味着它将卓殊任何大概用来路由二的请求。

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

固然UEnclaveL不相称在RouteTable群集中定义的其余路由对象,ASP.NET路由不管理请求。相反,管理被传送给三个ASP.NET
Page ,Web服务,或其它ASP.NET端点。

2.1二 路由二义性

只在同2个消除方案中,存在八个以及上述同等调节器下的同样action,当UCR-VL请求时,会冒出二义性。

贰义性德姆o目录结构

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

 从内容上来看,天性路由的始末与价值观路由大致,同样有路由U奥迪Q3L、路由值、调控器路由、路由约束和路由默许值等。鉴于篇幅限制,在此间就回顾的概述一下,不作详细演说,中期有时间可能有情侣须要,再论述。

 定义:性子路由便是将路由U帕杰罗L定义在调节器上或调节器内的格局上,而不像古板路由将路由U宝马7系L定义在RouteConfig.cs中。对比方下

图片 22

 

图片 23

三 路由生成U宝马X5L

 
 路由八个主要职务:相配传入的URubiconL请求和布局与特定路由对应的URubiconL,总结之相配UTucsonL和结构U卡宴L。在生成U中华VL时,生成URAV4L的意趣应该首先与采用用来生成UQashqaiL的路由相相称,那样路由就足以在管理传入或传播的URubiconL时成为完全的双向系统。原则上,开荒人士应该提供1组路由值,以便路由系统从中选中首个能够相称ULX570L的路由。

 三.一 U哈弗L生成的高层系概述

 
路由的着力是一个相当简单的算法,该算法基于多少个由RouteCollection类和RouteBase类组成的轻便抽象对象。能够行使二种措施来生成U路虎极光L,但那些点子都是调用RouteCollection.GetVirtualPath的三个重载方法而得了。RouteCollection.GetVirtulPath方法公有多个重载版本,上面的代码体现它们的形式具名:

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

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

(一)路由集结通过RouteBase.GetVirtualPath方法遍历每一个路由并访问:“能够调换给定参数的U汉兰达L吗”,这么些进度看似于在路由与传播请求相配时所选用的相配逻辑。

(贰)假如1个路由能够回答上边的主题素材(即相称),那么它就会回去3个暗含了U宝马X5L的VirTualPathData实例以及此外相配的新闻。不然,它就回去空值,路由体制移向列表中的下贰个路由。

其次个重载接受四个参数,在这之中第一个参数是路由名称。在路由集合中路由名称是唯一的,也正是说,未有三个例外的路由具有同等的称谓。当钦点了路由名称时,路由会集就不须求循环遍历每种路由,相反,它能够即时找到钦点名称的路由,并移向上边包车型地铁步子(2)。假若找到的路由无法同盟钦命的参数,该方法就会再次来到空值,并且不再相配其余路由。

  三.二  U猎豹CS陆L生成详解

 
(一)开荒人士调用像Html.ActionLink或Url.Action之类的主意,那些艺术反过来再调用RouteCollection.GetVirtualPath方法,并向它传递三个RequestContext对象、三个包罗值的字典以及用于选拔生成U安德拉L的路由名称(可选参数)。

 (2)路由体制查看须求的路由参数(即没有提供路由参数的暗中同意值),并保管提供的路由值字典为每多少个渴求的参数提供八个值,不然,U奥迪Q7L生成程序就会应声停下,并重回空值。

 (三)一些路由大概蕴涵未有对应路由参数的暗中同意值。如路由大概为category键提供私下认可值“pastries”,然则cateory不是路由U途锐L的三个参数,那种景象下,假设用户传入的路由值字典为category提供了一个值,那么该值必须相称category的暗许值。

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

(伍)路由非凡成!未来能够透过查看每四个路由参数,并尝试选择字典中的对应值填充相应参数,进而生成U宝马X3L。

可以回顾为如下流程图:

图片 24

 

四 路由绑定到操作

 在这一章节,主要分析UKoleosL绑定到调控器操作的平底细节,分析底层原理,精晓ASP.NET请求管道。注意,近期路由不仅仅只是ASP.NET
MVC的2个特点了,它曾经超先生越这几个界定,如ASP.NET Dynamic
Data。路由既不包罗MVC的内部知识,也不依附于MVC。

 肆.壹 高档次请求的路由管道

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

 
 (一)UrlRoutingModule尝试使用在RouteTable中注册的路由匹配当前恳请。

 
 (贰)借使RouteTable中有一个路由成功相称,路由模块就会从相称成功的路由中获得IRouteHandler接口对象。

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

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

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

4.贰 路由数量

   
调用GetRouteData方法会重回RouteData的3个实例。RouteData中富含了关于相称请求的路由音讯。

   
如U卡宴L:{Controller}/{action}/{id}。当请求/albums/list/1二叁传播时,该路由就会尝试相称传入的央浼,假设协作成功,它就创办3个字典,个中含有了从UENCOREL中剖析出的消息。确切地讲,路由还会向Values字典中为U途乐L中的每一种路由参数增添一个键;对于价值观路由{Controller}/{action}/{id},Values字典中应当至少含有四个键,分别是Controller,action和id,纵然传入的U哈弗L是对/albums/list/1贰三的伸手,路由就会分析该请求的UPRADOL,并为字典的键提供值。本例中,字典中“Controller”键的值为albums,”action”键的值为“list”,”id”键的值是“1贰3”;对于性子路由MVC使用DataTokens字典来囤积更可靠的新闻,而不是操作名称字符串。具体来讲,它蕴涵1个操作描述符列表,那一个描述符直接指向路由相称时也许行使的操作方法。对于调节器等第的性子路由,列表上校有持续二个操作。在任何MVC中都有接纳的RequestContext的RouteData属性保存着外面路由值。

5 路由调节和测试

 
 使用RouteDebugger调节和测试,启用RouteDebugger后,它会用七个DebuggerRouteHandler替换全部路由管理程序,DebugRouteHandler截获全体传入的请求,并查询路由表中的每3个路由,以便在页面头部呈现路由的会诊数据和参数。为利用RouteDebugger,只需在VS的Package
Manager Console窗口中利用NuGet安装就能够,命令Install-Package
routedebugger.。RouteDebugger包在增加Route
Debugger程序集的还要。也在web.config文件的appSettings节点中增加三个装置,用来拉开或禁止使用路由调节和测试。

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

 只要启用RouteDebugger,它就展现从(在地点栏中)当前乞请URAV四L中提取的路由数据。如此,能够在地点栏中输入种种UPRADOL,并查看输入的U本田UR-VL能与哪些路由至极,在页面尾部,它还会议及展览示一个饱含应用程序定义的所用路由列表,那样能够查看定义的哪个路由能够与日前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

陆 与路由有关的重大命名空间和类

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

图片 28

 陆.贰 Class
Reference( 路由涉及到的严重性类)

图片 29

 

7 总结

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

八 参考文献

 【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/。
  • 极少一些小说利用读书、参考、引用、抄袭、复制和粘贴等各个办法结合而成的,大多数为原创。
  • 如您喜欢,麻烦推荐一下;如您有新主见,接待提出,邮箱:二零一四177728@qq.com。
  • 能够转发该博客,但必须著名博客来源。

相关文章