一些人不想让外人精晓本人文件的路线,Identifier卡塔尔(英语:澳门最大线上娱乐State of Qatar)代表联独能源标记符

事例引进

§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
UCaymanLs.所以那也就从未有过门路对应的一定文件了.

You are given complete control of your U大切诺基L schema—that is, the set of
UMuranoLs 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
3.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(卡塔尔(英语:State of Qatar)鱼腥的时候, 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 URubiconL and use it to obtain an
IHttpHandler object that will handle the request.
早起的路由机制运作在框架的倡议处理管道. 它的劳作就是采取进来的UEnclaveL,
并用它来获取三个可见管理恳求的的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
.个中三个正是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

默许的路由是很日常的, 倘令你想要处理任何品类的UENCOREL, 你还需求做一些手脚.
我来举个简易的例证, 比如大家想要用UEnclaveL /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(卡塔尔(英语:State of Qatar). 你会意识那比选取routes.Add(new Route(…卡塔尔国卡塔尔(英语:State of Qatar) 方便超级多.

            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想要调用几个action方法,
它供给提供叁个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 9 and 12.
更确切的说,
action方法的参数不止只是轻便的第一手从RouteData.Values获取.
而是从模型绑定系统中收获,各个.net类型. 你会在第9章和12章中打探更多.

 

§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}七个暗中同意值, 它形成了四个强制的参数.
路由入口不再相配/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 });

那般, 当访谈的U福特ExplorerL有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的可选参数语法,
    你将不可能调控它的类型.(你会在接下去的生机勃勃章中打探更加多卡塔尔国
  • 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
    框架会将路由参数优先于查询字符串值.(你会在12章中学到值提供者和模型绑定卡塔尔国.
    所以,
    任何为page设置的路由值–纵然是null–也会预先于访谈page的询问字符串

UrlParameter.Optional消逝了那七个问题

 

§8.2.5  Using Constraints

突发性, 你会想要加多额外的规格, 以同盟特定的route. 比如:

  • 你想相称get诉求, 并不是post乞请
  • 一些参数要合作特定的参数(e.g. ID参数必得同盟数字类型卡塔尔(英语:State of Qatar)
  • 局部route用来相配常规的web浏览器发来的倡议,
    有的匹配iphone发来的均等UHavalL

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就可以相称 /阿特icles/1 和 /阿特icles/123456 这两连串型,
实际不是其它的,(这里的正则表明式表示的是: 数字类型,1~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 URI、URL与URN

 1.1 URI、URL和URN定义 

     U宝马7系I(Uniform Resource
Identifier卡塔尔(英语:State of Qatar)代表联独能源标志符,标记财富的字符串;

     U牧马人L (Uniform Resource
Locator卡塔尔代表联独财富定位符,互联英特网标准财富的地址;

     UMuranoN(Uniform Resources
Name卡塔尔(英语:State of Qatar)代表联独财富名称,互连网络能源的名号;

 1.2 U翼虎I、U昂科威L和U卡宴N三者之间的关联图

澳门最大线上娱乐 5

1.3 对URAV4I、UXC90L和UHighlanderN三者之间分析

      本拆解深入分析基于1.2
UQX56I、UMuranoL和U兰德酷路泽N三者之间的涉嫌图。

     
(1卡塔尔(英语:State of Qatar)从命名角度,URI标记能源且唯生龙活虎,UEscortL标志能源地址
,U宝马7系N标志财富名称;

     
(2卡塔尔国从数学关系:U牧马人I=UENCOREL+U讴歌MDXN+UTiguanL∩UEnclaveN;相当轻便见到,UHighlanderL一定是UHavalI,但U奥迪Q3I不自然是U奇骏L,同理,U奥迪Q5N一定是U奥迪Q5I,但U讴歌ZDXI不确定是U凯雷德N;

1.4 U瑞虎L应怀有特色

     (1卡塔尔  域名便于回想和拼写;

     (2)  简短;

     (3卡塔尔  便于输入;

     (4卡塔尔(英语:State of Qatar)  能够显示出站点布局;

     (5卡塔尔(英语:State of Qatar) 应该是“可破解的”,客户能够透过移除UENCOREL的结尾,进而到达越来越高档期的顺序的新闻连串布局;

     (6)  长久、不能够退换

1.5  小结

     
 经常状态下,U福睿斯I代表同意财富标志符(Uniform Resource
Identifier卡塔尔(英语:State of Qatar)。URAV4I是标记了二个财富的字符串。从技巧角度看,全数URAV4L都是UPRADOI。W3C以为“UHighlanderL是贰个非正式的概念,但它极其实惠:U途睿欧L是U奥德赛I的风流倜傥种类型,它经过代表自个儿的关键寻访机制来标志能源”,换句话说,U奔驰G级I是某种能源的标记符,而UTucsonL则为获得该能源提供了具体的音讯。

     
 注释:能源是三个抽象概念,既可以够指二个文件,也能够指方法调用的结果或服务器上的风姿浪漫对别样内容。

2 路由概述(守旧路由卡塔尔(英语:State of Qatar)

2.1  WebForm URL与Route URL

   
 (1卡塔尔(英语:State of Qatar)WebForm中,对U宝马7系L的传布央浼常常映射到磁盘上的物理文件,如.aspx文件。比如对http://server/application/Product.aspx?id=4的请求映射到名为Products.aspx文件,该文件包含代码和标记用于呈现对浏览器的响应,一般请求示过程抽象如下:

   
 澳门最大线上娱乐 6

     (2卡塔尔国ASP.NET
MVC中,日常地,ULANDL映射而不是映射到实际磁盘上的情理文件,那是依附ASP.NET路由个性,首要有七个进度,即UENVISIONL映射和UHighlanderL生成(接下去批注)。在ASP.NET路由中,您能够定义URAV4L形式,该情势满含在拍卖UCR-VL需要时选拔的值的占位符。在运作时,运用程序名称前边的U逍客L部分依照你所定义的U宝马X3L形式解析为离散值。比如,在伸手http://server/application/Products/show/beverages时,路由分析器可以将值Products、show和beverages传递给请求的处理程序。相反,在一个不由URL路由管理的请求中,/Products/show/beverages片段将被解释为运用程序中的一个文件的路径。
  

2.2  ASP.NET 路由与 URL 重写

        ASP.NET 路由分裂于别的 U本田UR-VL
重写方案。UENCOREL 重写通过在将呼吁发送到网页早先实际改正 U途胜L
来拍卖传入哀求。比方,二个选用 UMuranoL 重写的应用程序大概会将 URAV4L 从 /Products/Widgets/ 校正为 /Products.aspx?id=4。别的,U途睿欧L 重写平常未有相应的 API
来创建基于方式的 UTiggoL。在 U福睿斯L 重写中,借使更换了 UHavalL
形式,则必得手动更新包蕴原始 UTiggoL 的有着超链接。由于
ASP.NET 路由得以从 URL 提取值,所以拍卖传入须求时不修正UCR-VL。假设非得创制三个 UEvoqueL,则将参数值传递到为你生成 UTiguanL
的法门中。若要更正 UEscortL
格局,请在某地点变动该情势,您在应用程序中开创的基于该方式的具备链接将自动使用新情势。

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.

     
 译文:路由是风流倜傥种被映射到某些管理程序的UEscortL格局。管理程序恐怕是三个大要文件,如在WebForms运用程序中的aspx文件。管理程序也会有可能是一个管理央浼的类,如MVC应用程序中的调节器。要定义路由,您能够由此点名UCRUISERL格局、处理程序和路径的名号来成立路由类的实例。

      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包罗了早期安插的UHighlanderL路由。那么些都是在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参数卡塔尔国。文字和占位符坐落于UTiggoL的意气风发部分中,由斜杠(/卡塔尔字符分隔。

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.

译文:当发出诉求时,URL被深入分析为局地和占位符,且变量值被提必要央浼管理程序。那个历程看似于查询字符串中的数据被剖析并传递给央浼处理程序的法子。在此二种情景下,变量消息都含有在U宝马7系L中,并以键值对的样式传递给管理程序。对于查询字符串,键和值都在U传祺L中。对于路由,键是UHavalL方式中定义的占位符名称,在USportageL中唯有是值。

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.

译文:在UQX56L格局中,通过将它们封装在括号(以致卡塔尔(قطر‎中来定义占位符。您能够在三个段中定义多个占位符,可是必需用文字值分隔它们。比方,语言-国家/行动是风流倜傥种有效的路线方式。但是,语言国家/action不是多个可行的情势,因为占位符之间一向不文字值或分隔符。由此,路由不可能说了算将语言占位符的值与国家占位符的值分隔开分离。

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运用程序中,路由UKoleosL方式经常包涵调控器和动作占位符。

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中的调节器值增添后缀“调控器”来鲜明要调用哪个调整器,以明确调节器的花色名称,该调控器将拍卖乞求。U昂CoraL中的操作值决定调用哪个操作方法。

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.

译文:比方,二个分包UPRADOL路线  /成品的U大切诺基L映射到三个名字为ProductsController的调节器。action参数中的值是调用的操作方法的名目。三个暗含U巴博斯 CL级L路径  /付加物/show
 的UPRADOL会以致对ProductsController类的Showmethod的调用。

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

译文:下表显示了暗许的UQashqaiL情势,它显得了由暗中同意路由拍卖的U福睿斯L恳求的身体力行。

 澳门最大线上娱乐 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
6.0,您必须加多.mvc文件扩大名到UMuranoL格局中,如上边包车型大巴例证:

 澳门最大线上娱乐 9

 如在VS二〇一三采纳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方法创立叁个路由对象并将其加多到RouteCollection对象。您能够在传递给MapPageRoute方法的参数中内定路由对象的性情。

Typically, you add routes in a method
that is called from the handler for the Application_Start event in the
Global.asax file. This approach makes sure that the routes are available
when the application starts. It also enables you to call the method
directly when you unit-test the application. If you want to call a
method directly when you unit-test the application, the method that
registers the routes must be static (Shared in Visual Basic) and must
have a RouteCollection parameter.

译文:平常地,在全局Global.asax文件中,您能够在多少个叫做Application_Start
方法里增添路由。该方法确定保障当应用程序运行时,路由是基本上能用的。它还使您能够在对应用程序进行单元测量检验时直接调用该办法。要是您想在对应用程序进行单元测验时直接调用方法,那么注册路由的章程必需是静态的(在Visual
Basic中是分享的卡塔尔,而且必得具备三个路由参数。

The following example shows code from a
Global.asax file that adds a Route object that defines two URL
parameters named action and categoryName. URLs that have the specified
pattern are directed to the physical page named Categories.aspx.

译文:上面包车型客车现身说法展现了来自.Globalasax文件的代码,该代码加多了一个路由对象,该对象定义了五个名字为action和类型称号的U索罗德L参数。具有钦赐方式的url被定向到名叫分类.aspx的大要页面。

protected void Application_Start(object sender, EventArgs e)
{
    RegisterRoutes(RouteTable.Routes);
}

public static void RegisterRoutes(RouteCollection routes)
{
    routes.MapPageRoute("",
        "Category/{action}/{categoryName}",
        "~/categoriespage.aspx");
}

2.6 Adding Routes to an MVC
Application

 If you adopt the MVC convention of
implementing controllers by creating classes that derive from the
ControllerBase class and giving them names that end with “Controller”,
you do not need to manually add routes in an MVC application. The
preconfigured routes will invoke the action methods that you implement
in the controller classes.

译文:要是你通过创办从调控器基类派生的类来落成调控器的MVC约定,并给它们以“调节器”结尾的名称,那么您就没有必要在MVC应用程序中手动加多路由了。预配置的路由将调用您在支配器类中完成的操作方法。

If you want to add custom routes in an
MVC application, you use the MapRoute(RouteCollection, String, String)
method instead of the MapPageRoute(String, String, String)
method.
译文:借令你想在MVC应用程序中增多自定义路由,您能够接收MapRoute(RouteCollection、String、String卡塔尔(قطر‎方法,并非MapPageRoute(字符串、字符串、字符串卡塔尔(قطر‎方法。

The following example shows the code that
creates default MVC routes in the Global.asax file, as defined in the
Visual Studio project template for MVC applications.

 译文:上面包车型客车事例呈现了在大局中开创默许MVC路由的代码。asax文件,正如在Visual
Studio项目模板中定义的MVC应用程序。

public class MvcApplication : System.Web.HttpApplication
{
    public static void RegisterRoutes(RouteCollection routes)
    {
        routes.IgnoreRoute("{resource}.axd/{*pathInfo}");

        routes.MapRoute(
            "Default",                                              // Route name 
            "{controller}/{action}/{id}",                           // URL with parameters 
            new { controller = "Home", action = "Index", id = "" }  // Parameter defaults
        );

    }

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

2.7 Setting Default Values for U奥迪Q5L
Parameters(为UCRUISERL参数设置私下认可值卡塔尔

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.

译文:当您定义一个路由时,您能够为四个参数钦点一个暗许值。倘使该参数的值未有包罗在U奥迪Q7L中,则运用暗中同意值。通过将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.

2.8 Handling a Variable Number of Segments
in a UEscortL Pattern(在UENCOREL方式中处理可变多少的段卡塔尔(قطر‎

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.

译文:偶尔你必需管理富含一个可变多少的UPAJEROL段的UEscortL伏乞,当中。当您定义一个路由时,您能够钦赐,即便一个U安德拉L的部分比情势中有越来越多的段,那么额外的段被认为是最终一片段的大器晚成部分。要以这种方法管理额外的段,您能够用星号(*卡塔尔(قطر‎标识最后二个参数。这被叫做叁个暧昧的参数。二个带有全体参数的路由也将合营不带有最终叁个参数的任何值的url。上边的现身说法体现了八个极其未分明的数量的段的路由格局。

/ query / { queryname } { * queryvalues
}

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

译文:当ASP.NET路由拍卖多个U奥迪Q3L央浼时,示例中所示的路由定义产生了下表中列出的结果。

澳门最大线上娱乐 12

2.9  Adding Constraints to
Routes(为路由增加封锁卡塔尔

In addition to matching a URL request to
a route definition by the number of parameters in the URL, you can
specify that values in the parameters meet certain constraints. If a URL
contains values that are outside the constraints for a route, that route
is not used to handle the request. You add constraints to make sure that
the URL parameters contain values that will work in your
application.

译文:除了通过UWranglerL中参数的数额来相称ULacrosseL必要外,还足以钦赐参数中的值满意一定的节制规范。假诺叁个UMuranoL富含的值超过了路由的束缚,那么该路由就不会被用于拍卖央浼。您添加了有的封锁,以保障UENVISIONL参数包蕴在你的应用程序中央银行事的值。
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路由艺术。卡塔尔(英语:State of Qatar)

 

 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(不应用路由时的场合卡塔尔(英语:State of Qatar)

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 UTucsonL Pattern(找到与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
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
U奇骏L Pattern(为ULANDL情势显式禁止使用路由卡塔尔

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陆风X8L央求。通过定义一条路由,并钦点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 U奇骏Ls Are Matched to
Routes(url怎么样与路由优质卡塔尔(英语:State of Qatar)

When routing handles URL requests, it
tries to match the URL of the request to a route. Matching a URL request
to a route depends on all the following conditions:

译文:当路由拍卖UEscortL央求时,它尝试将呼吁的UTiguanL与路由特别。将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
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永恒不会管理央浼,因为路由1率先被相配,它连接相配大概在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永久不会处理央求。第1条大概是针对性每月报告的,而路由2或许是指向年度报告的。可是,路由第11中学的私下认可值意味着它将相配任何也许用于路由2的乞请。

You can avoid ambiguity in the patterns
by including constants, such as annual/{report}/{year} and
monthly/{report}/{year}/{month}.
If a URL does not match any Route object
that is defined in the RouteTable collection, ASP.NET routing does not
process the request. Instead, processing is passed to an ASP.NET page,
Web service, or other ASP.NET endpoint.

译文:您能够通过包括常量来幸免格局中的歧义,比方annual/{report}/{year} and monthly/{report}/{year}/{month}。

假设UHavalL不宽容在RouteTable集结中定义的别样路由对象,ASP.NET路由不管理央求。相反,管理被传送给一个ASP.NET
Page ,Web服务,或别的ASP.NET端点。

2.12 路由二义性

只在同叁个施工方案中,存在三个以至上述同等调控器下的相近action,当U智跑L必要时,会并发二义性。

二义性德姆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

3 路由概述(性子路由卡塔尔(قطر‎

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

 从内容上来看,本性路由的内容与历史观路由大约,相似有路由UENVISIONL、路由值、调整器路由、路由节制和路由暗许值等。鉴于篇幅限定,在这里地就轻松的概述一下,不作详细解说,早先时期不时光仍然有心上人须要,再论述。

 定义:特性路由就是将路由U汉兰达L定义在调节器上或调控器内的法门上,而不像守旧路由将路由ULANDL定义在RouteConfig.cs中。对例如下

澳门最大线上娱乐 22

 

澳门最大线上娱乐 23

3 路由生成U中华VL

 
 路由八个主要任务:相配传入的ULacrosseL乞求和组织与特定路由对应的UTucsonL,回顾之相称U途乐L和构造U普拉多L。在生成U奥迪Q5L时,生成UWranglerL的情致应该首先与选拔用来生成UHighlanderL的路由相相称,那样路由就足以在拍卖传入或传播的U索罗德L时改为完全的双向系统。原则上,开辟人士应该提供意气风发组路由值,以便路由系统从当中选中第二个能够相配UEscortL的路由。

 3.1 UPRADOL生成的高层系概述

 
路由的为主是一个特轻便的算法,该算法基于三个由RouteCollection类和RouteBase类组成的简便抽象对象。能够利用四种方式来生成UTucsonL,但那个措施都是调用RouteCollection.GetVirtualPath的叁个重载方法而甘休。RouteCollection.GetVirtulPath方法公有五个重载版本,下边包车型大巴代码显示它们的秘技签字:

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

 第一个重载版本选拔当前的RequestContext,以至由客户钦点的路由值(字典卡塔尔(قطر‎。

(1卡塔尔(英语:State of Qatar)路由集结通过RouteBase.GetVirtualPath方法遍历各种路由并拜会:“能够改变给定参数的U帕杰罗L吗”,这么些进程看似于在路由与传播央求相配时所接收的合营逻辑。

(2卡塔尔国若是一个路由能够回复上边的标题(即相配卡塔尔国,那么它就能够回到一个蕴含了UGL450L的VirTualPathData实例以致任何相配的新闻。不然,它就再次回到空值,路由体制移向列表中的下叁个路由。

第二个重载接纳四个参数,在那之中第二个参数是路由名称。在路由会集西路由名称是必定要经过的地方的,也便是说,未有五个例外的路由拥有相像的名称。当钦点了路由名称时,路由群集就不须求循环遍历种种路由,相反,它能够马上找到内定名称的路由,并移向上边包车型地铁步骤(2卡塔尔(قطر‎。借使找到的路由无法协作钦定的参数,该办法就能够回去空值,并且不再相配别的路由。

  3.2  UENCOREL生成详整

 
(1卡塔尔(قطر‎开垦职员调用像Html.ActionLink或Url.Action之类的情势,这个方法反过来再调用RouteCollection.GetVirtualPath方法,并向它传递三个RequestContext对象、一个含有值的字典以至用于接纳生成U讴歌ZDXL的路由名称(可选参数卡塔尔。

 (2卡塔尔(英语:State of Qatar)路由体制查看必要的路由参数(即未有提供路由参数的暗许值卡塔尔国,并保证提供的路由值字典为每一个供给的参数提供叁个值,不然,U翼虎L生成程序就能够马上停止,并赶回空值。

 (3卡塔尔(قطر‎一些路由大概带有没有对应路由参数的暗中认可值。如路由恐怕为category键提供暗中同意值“pastries”,不过cateory不是路由UENVISIONL的三个参数,这种情景下,假诺顾客传入的路由值字典为category提供了一个值,那么该值必需相称category的暗中同意值。

 (4卡塔尔然后路由系统使用路由约束。

(5卡塔尔国路由特别成!以后能够透过查看每三个路由参数,并尝试接收字典中的对应值填充相应参数,从而生成UV8 VantageL。

能够回顾为如下流程图:

澳门最大线上娱乐 24

 

4 路由绑定到操作

 在这里生机勃勃章节,首要深入分析UTiggoL绑定到调节器操作的平内故事情节,深入分析底层原理,精通ASP.NET乞求管道。注意,近些日子路由不独有只是ASP.NET
MVC的壹本性情了,它早就当先那些约束,如ASP.NET Dynamic
Data。路由既不包含MVC的当中级知识分子识,也不注重于MVC。

 4.1 高档期的顺序诉求的路由管道

  当ASP.NET
拍卖伏乞时,路由管道首要由以下几步组成:

 
 (1卡塔尔UrlRoutingModule尝试使用在RouteTable中登记的路由相配当前呼吁。

 
 (2卡塔尔国倘若RouteTable中有多个路由中标相称,路由模块就能够从匹配成功的路由中获取IRouteHandler接口对象。

 
 (3卡塔尔(英语:State of Qatar)路由模块调用IRouteHandler接口的GetHandler方法,并回到用来管理诉求的IHttpHandler对象。

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

   (5卡塔尔(قطر‎在ASP.NET
MVC中,IRouteHandler是MvcRouteHandler类的一个实例,MvcRouteHandler转而回到二个兑现了IHttpHandler接口的MvcHandler对象。再次回到的MvcHandler对象首要用以实例化调控器,并调
       用该实例化的调整器上的操作方法。

4.2 路由数据

   
调用GetRouteData方法会重返RouteData的二个实例。RouteData中含有了关于相称诉求的路由音信。

   
如USportageL:{Controller}/{action}/{id}。当央求/albums/list/123流传时,该路由就能尝试相称传入的央求,假诺合作成功,它就创设叁个字典,此中积攒了从U宝马7系L中剖析出的音信。确切地讲,路由还可能会向Values字典中为U奇骏L中的各种路由参数增加二个键;对于古板路由{Controller}/{action}/{id},Values字典中应该最少含有八个键,分别是Controller,action和id,假若传入的UPAJEROL是对/albums/list/123的乞请,路由就能深入分析该乞请的U昂CoraL,并为字典的键提供值。本例中,字典中“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,它就显示从(在地点栏中卡塔尔当前乞求U宝马X5L中领取的路由数据。如此,能够在地点栏中输入各个U陆风X8L,并查看输入的U福特ExplorerL能与哪些路由优良,在页面尾部,它还博览会示多个暗含应用程序定义的所用路由列表,那样能够查阅定义的哪个路由可以与眼下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 与路由相关的最首要命名空间和类

 6.1  路由涉及的命名空间

澳门最大线上娱乐 28

 6.2 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/2为原创。
  • 如您爱怜,麻烦推荐一下;如你有新主张,迎接提议,邮箱:二〇一五177728@qq.com。
  • 能够转发该博客,但必得有名博客来源。

相关文章