Locator)代表联独资源定位符,有的人不想让别人知道自己文件的门径

事例引入

§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
URLs.所以这也就不曾门路对应的一定文件了.

You are given complete control of your URL schema—that is, the set of
URLs 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()鱼腥的时候, 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 URL and use it to obtain an
IHttpHandler object that will handle the request.
早起的路由机制运行在框架的伸手处理管道. 它的做事就是接纳进来的URL,
并用它来赢得一个可以处理请求的的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 URL is requested, the system invokes each of the IHttpModules
registered for the application. 当一个URL被呼吁,
系统调用每个在应用程序中早就注册的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

默认的路由是很平时的, 假设你想要处理任何项目的URL, 你还需要做一些手脚.
我来举个简易的例证, 比如我们想要用URL /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想要调用一个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 });

这样, 当访问的URL有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参数必须配合数字类型)
  • 部分route用来匹配常规的web浏览器发来的伸手,
    有的匹配iphone发来的一模一样URL

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/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 被看做一个URL模型, 就像一个普通的路由入口. 

注:该例子没有参预区域

1 URI、URL与URN

 1.1 URI、URL和URN定义 

     URI(Uniform Resource
Identifier)代表统一资源标识符,标识资源的字符串;

     URL (Uniform Resource
Locator)代表联合营源定位符,互联网上规范资源的地址;

     URN(Uniform Resources
Name)代表统一资源名称,互联网上资源的名目;

 1.2 URI、URL和URN三者之间的涉嫌图

公海赌船网址 5

1.3 对URI、URL和URN三者之间解析

      本解析基于1.2
URI、URL和URN三者之间的涉及图。

     
(1)从命名角度,URI标识资源且唯一,URL标识资源地址
,URN标识资源名称;

     
(2)从数学关系:URI=URL+URN+URL∩URN;很容易看到,URL一定是URI,但URI不肯定是URL,同理,URN一定是URI,但URI不必然是URN;

1.4 URL应持有特色

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

     (2)  简短;

     (3)  便于输入;

     (4)  可以反映出站点布局;

     (5)
 应该是“可破解的”,用户可以由此移除URL的末段,进而到达更高层次的新闻序列布局;

     (6)  持久、不可以更改

1.5  小结

     
 平时情况下,URI代表同意资源标识符(Uniform Resource
Identifier)。URI是标识了一个资源的字符串。从技术角度看,所有URL都是URI。W3C认为“URL是一个非正式的定义,但它充足管用:URL是URI的一种档次,它经过代表本身的第一走访机制来标识资源”,换句话说,URI是某种资源的标识符,而URL则为拿到该资源提供了具体的信息。

     
 注释:资源是一个抽象概念,既可以指一个文件,也可以指方法调用的结果或服务器上的部分其他内容。

2 路由概述(传统路由)

2.1  WebForm URL与Route URL

   
 (1)WebForm中,对URL的扩散请求平常映射到磁盘上的大体文件,如.aspx文件。例如对http://server/application/Product.aspx?id=4的请求映射到名为Products.aspx文件,该文件包含代码和标记用于呈现对浏览器的响应,一般请求示过程抽象如下:

   
 公海赌船网址 6

     (2)ASP.NET
MVC中,平日地,URL映射并非映射到现实磁盘上的物理文件,这是基于ASP.NET路由特性,重要有六个过程,即URL映射和URL生成(接下去讲解)。在ASP.NET路由中,您可以定义URL情势,该形式涵盖在拍卖URL请求时拔取的值的占位符。在运转时,运用程序名称前边的URL部分按照你所定义的URL形式分析为离散值。例如,在伏乞http://server/application/Products/show/beverages时,路由分析器可以将值Products、show和beverages传递给请求的处理程序。相反,在一个不由URL路由管理的请求中,/Products/show/beverages片段将被解释为运用程序中的一个文件的路径。
  

2.2  ASP.NET 路由与 URL 重写

        ASP.NET 路由不同于其他 URL
重写方案。URL 重写通过在将请求发送到网页从前实际更改 URL
来处理传入请求。例如,一个行使 URL 重写的应用程序可能会将 URL 从 /Products/Widgets/ 更改为 /Products.aspx?id=4。其余,URL 重写通常没有对号入座的 API
来创建基于情势的 URL。在 URL 重写中,假诺改动了 URL
形式,则必须手动更新包含原始 URL 的拥有超链接。由于
ASP.NET 路由得以从 URL 提取值,所以拍卖传入请求时不更改
URL。倘诺非得创建一个 URL,则将参数值传递到为你生成 URL
的点子中。若要更改 URL
情势,请在某地点变动该格局,您在应用程序中创设的基于该形式的有所链接将自行使用新格局。

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.

     
 译文:路由是一种被映射到某个处理程序的URL情势。处理程序可能是一个物理文件,如在WebForms运用程序中的aspx文件。处理程序也恐怕是一个处理请求的类,如MVC应用程序中的控制器。要定义路由,您可以透过点名URL形式、处理程序和路线的名称来创制路由类的实例。

      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包含了先行布置的URL路由。那多少个都是在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.

译文:URL情势或者含有文字值和变量占位符(称为URL参数)。文字和占位符位于URL的片段中,由斜杠(/)字符分隔。

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被解析为部分和占位符,且变量值被提供给请求处理程序。这几个历程看似于查询字符串中的数据被分析并传递给请求处理程序的格局。在这二种状态下,变量音讯都含有在URL中,并以键值对的样式传递给处理程序。对于查询字符串,键和值都在URL中。对于路由,键是URL形式中定义的占位符名称,在URL中单单是值。

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.

译文:在URL格局中,通过将它们封装在括号(以及)中来定义占位符。您可以在一个段中定义两个占位符,不过必须用文字值分隔它们。例如,语言-国家/行动是一种有效的门路格局。可是,语言国家/action不是一个实用的格局,因为占位符之间从未文字值或分隔符。由此,路由无法说了算将语言占位符的值与国家占位符的值分隔开。

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

下表突显了实惠的路由形式和与格局匹配的URL请求示例。

公海赌船网址 7

 Typical URL Patterns in MVC
Applications

译文:MVC运用程序中的经典情势

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

译文:在MVC运用程序中,路由URL形式平时包含控制器和动作占位符。

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处理程序通过向URL中的控制器值添加后缀“控制器”来规定要调用哪个控制器,以确定控制器的类型名称,该控制器将拍卖请求。URL中的操作值决定调用哪个操作方法。

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.

译文:例如,一个包含URL路径  /产品
的URL映射到一个名为ProductsController的控制器。action参数中的值是调用的操作方法的称谓。一个含有URL路径
  /产品/show
 的URL会促成对ProductsController类的Showmethod的调用。

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

译文:下表突显了默认的URL情势,它显得了由默认路由拍卖的URL请求的言传身教。

 公海赌船网址 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文件扩充名到URL情势中,如下边的事例:

 公海赌船网址 9

 如在VS2013使用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和类型称号的URL参数。具有指定形式的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 URL
Parameters(为URL参数设置默认值)

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

译文:当你定义一个路由时,您可以为一个参数指定一个默认值。假诺该参数的值没有包含在URL中,则运用默认值。通过将dictionary对象分配给route类的默认属性,能够为路由安装默认值。下面的例证彰显了怎么样通过采用MapPageRoute(字符串、字符串、字符串、布尔值、RouteValueDictionary)方法添加具有默认值的路由。

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 URL Pattern(在URL情势中处理可变多少的段)

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.

译文:有时你必须处理包含一个可变多少的URL段的URL请求,其中。当你定义一个路由时,您可以指定,假使一个URL的局部比情势中有更多的段,那么额外的段被认为是终极一有些的一有些。要以这种措施处理额外的段,您可以用星号(*)标记最终一个参数。这被称呼一个笼统的参数。一个富含所有参数的路由也将配合不带有最后一个参数的任何值的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路由拍卖一个URL请求时,示例中所示的路由定义发生了下表中列出的结果。

公海赌船网址 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.

译文:除了通过URL中参数的数码来匹配URL请求外,还可以够指定参数中的值满意一定的自律原则。如若一个URL包含的值超出了路由的束缚,那么该路由就不会被用于拍卖请求。您添加了一些束缚,以担保URL参数包含在你的应用程序中行事的值。
Constraints are defined by using regular
expressions or by using objects that implement the IRouteConstraint
interface. When you add the route definition to the Routes collection,
you add constraints by creating a RouteValueDictionary object that
contains the verification test. The key in the dictionary identifies the
parameter that the constraint applies to. The value in the dictionary
can be either a string that represents a regular expression or an object
that implements the IRouteConstraint interface.

译文:约束是因而采用正则表明式或行使实现IRouteConstraint接口的目的来定义的。当将路由定义添加到路由集合时,通过成立一个包含验证测试的RouteValueDictionary对象来丰硕约束。字典中的键标识约束应用到的参数。字典中的值能够是表示正则表明式的字符串,也得以是贯彻IRouteConstraint接口的目的。
If you provide a string, routing treats
the string as a regular expression and checks whether the parameter
value is valid by calling the IsMatch method of the Regex class. The
regular expression is always treated as case-insensitive. For more
information, see .NET Framework Regular Expressions.

译文:假设您提供一个字符串,那么路由将字符串作为一个正则表达式来拍卖,并经过调用Regex类的IsMatch方法检查参数值是否有效。正则表明式总是被视为不区分轻重缓急写的。要询问更多音讯,请参阅。净框架正则表达式。
If you provide an IRouteConstraint
object, ASP.NET routing checks whether the parameter value is valid by
calling the Match method of the IRouteConstraint object. The Match
method returns a Boolean value that indicates whether the parameter
value is valid.

译文:即使您提供一个IRouteConstraint对象,ASP.NET
路由通过调用IRouteConstraint对象的配合方法,
以此来检查参数值是否可行。Match方法再次来到一个布尔值,该值表示参数值是否行得通。
The following example shows how to use
the MapPageRoute method to create a route that has constraints that
limit what values can be included in the locale and year parameters. (In
an MVC application, you would use the MapRoute method.)

译文:下边的言传身教体现了哪些行使MapPageRoute方法创设一条路子,该路由限制了地区和年参数中可以涵盖的值。(在MVC应用程序中,您将应用map路由艺术。)

 

 1 public static void RegisterRoutes(RouteCollection routes)
 2 {
 3     routes.MapPageRoute("",
 4         "Category/{action}/{categoryName}",
 5         "~/categoriespage.aspx",
 6         true,
 7         new RouteValueDictionary 
 8             {{"categoryName", "food"}, {"action", "show"}},
 9         new RouteValueDictionary 
10             {{"locale", "[a-z]{2}-[a-z]{2}"},{"year", @"\d{4}"}}
11        );
12 }

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

公海赌船网址 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 URL Pattern(找到与URL情势匹配的物理文件)

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
URL Pattern(为URL格局显式禁用路由)

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  

译文:您还是可以够指定路由不应当处理某些URL请求。通过定义一条路由,并点名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 URLs 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:

译文:当路由拍卖URL请求时,它尝试将呼吁的URL与路由分外。将URL请求匹配到路由取决于以下标准:

  • 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也许是针对年度报告的。可是,路由1中的默认值意味着它将匹配任何可能用于路由2的乞请。

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

译文:您可以经过包含常量来避免情势中的歧义,例如
annual/{report}/{year} and monthly/{report}/{year}/{month}。

假设URL不般配在RouteTable集合中定义的此外路由对象,ASP.NET路由不处理请求。相反,处理被传送给一个ASP.NET
Page ,Web服务,或其余ASP.NET端点。

2.12 路由二义性

只在同一个缓解方案中,存在六个以及上述同等控制器下的相同action,当URL请求时,会产出二义性。

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

3 路由概述(特性路由)

 特性路由是在ASP.NET MVC
5中新增的,传统路由ASP.NET MVC 1中就有了。

 从内容上来看,特性路由的情节与观念路由差不多,同样有路由URL、路由值、控制器路由、路由约束和路由默认值等。鉴于篇幅限制,在此处就简单的概述一下,不作详细阐释,中期有时间或者有对象需要,再论述。

 定义:特性路由就是将路由URL定义在控制器上或控制器内的方法上,而不像传统路由将路由URL定义在RouteConfig.cs中。比较如下

公海赌船网址 22

 

公海赌船网址 23

3 路由生成URL

 
 路由四个重要职责:匹配传入的URL请求和结构与一定路由对应的URL,概括之匹配URL和社团URL。在生成URL时,生成URL的意思应该率先与采用用来生成URL的路由相匹配,这样路由就足以在处理传入或传播的URL时改为完全的双向系统。原则上,开发人士应该提供一组路由值,以便路由系统从中选中第一个可以匹配URL的路由。

 3.1 URL生成的高层系概述

 
路由的中坚是一个相当简单的算法,该算法基于一个由RouteCollection类和RouteBase类组成的简便抽象对象。可以运用多种办法来生成URL,但这多少个方法皆以调用RouteCollection.GetVirtualPath的一个重载方法而告终。RouteCollection.GetVirtulPath方法公有四个重载版本,上面的代码体现它们的章程签名:

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

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

(1)路由集合通过RouteBase.GetVirtualPath方法遍历每个路由并走访:“能够变动给定参数的URL吗”,这一个历程看似于在路由与传播请求匹配时所采纳的匹配逻辑。

(2)假诺一个路由可以回答上边的问题(即匹配),那么它就会回来一个包含了URL的VirTualPathData实例以及其它匹配的音信。否则,它就回去空值,路由体制移向列表中的下一个路由。

第二个重载接受五个参数,其中第二个参数是路由名称。在路由集合中路由名称是唯一的,也就是说,没有五个不同的路由具有相同的称呼。当指定了路由名称时,路由集合就不需要循环遍历每个路由,相反,它可以即刻找到指定名称的路由,并移向上边的步调(2)。如若找到的路由无法匹配指定的参数,该措施就会回到空值,并且不再匹配其他路由。

  3.2  URL生成详解

 
(1)开发人员调用像Html.ActionLink或Url.Action之类的点子,这么些点子反过来再调用RouteCollection.GetVirtualPath方法,并向它传递一个RequestContext对象、一个暗含值的字典以及用于选取生成URL的路由名称(可选参数)。

 (2)路由体制查看要求的路由参数(即没有提供路由参数的默认值),并确保提供的路由值字典为每一个要求的参数提供一个值,否则,URL生成程序就会登时终止,并赶回空值。

 (3)一些路由可能包含没有对应路由参数的默认值。如路由可能为category键提供默认值“pastries”,然而cateory不是路由URL的一个参数,这种情况下,假若用户传入的路由值字典为category提供了一个值,那么该值必须匹配category的默认值。

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

(5)路由十分成!现在得以经过查阅每一个路由参数,并尝试采用字典中的对应值填充相应参数,进而生成URL。

可以概括为如下流程图:

公海赌船网址 24

 

4 路由绑定到操作

 在这一章节,重要分析URL绑定到控制器操作的底部细节,分析底层原理,精通ASP.NET请求管道。注意,如今路由不仅仅只是ASP.NET
MVC的一个风味了,它曾经超过这么些界定,如ASP.NET Dynamic
Data。路由既不包括MVC的其中知识,也不依靠于MVC。

 4.1 高层次请求的路由管道

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

 
 (1)UrlRoutingModule尝试使用在RouteTable中登记的路由匹配当前呼吁。

 
 (2)假如RouteTable中有一个路由中标匹配,路由模块就会从匹配成功的路由中获取IRouteHandler接口对象。

 
 (3)路由模块调用IRouteHandler接口的GetHandler方法,并重临用来处理请求的IHttpHandler对象。

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

   (5)在ASP.NET
MVC中,IRouteHandler是MvcRouteHandler类的一个实例,MvcRouteHandler转而回到一个落实了IHttpHandler接口的MvcHandler对象。重返的MvcHandler对象紧要用于实例化控制器,并调
       用该实例化的控制器上的操作方法。

4.2 路由数据

   
调用GetRouteData方法会再次回到RouteData的一个实例。RouteData中富含了关于匹配请求的路由消息。

   
如URL:{Controller}/{action}/{id}。当请求/albums/list/123流传时,该路由就会尝试匹配传入的央求,假如匹配成功,它就创建一个字典,其中蕴蓄了从URL中分析出的音讯。确切地讲,路由还会向Values字典中为URL中的每个路由参数添加一个键;对于传统路由{Controller}/{action}/{id},Values字典中应有至少含有多少个键,分别是Controller,action和id,即便传入的URL是对/albums/list/123的请求,路由就会分析该请求的URL,并为字典的键提供值。本例中,字典中“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,它就显得从(在地方栏中)当前恳请URL中领到的路由数据。如此,可以在地点栏中输入各种URL,并查阅输入的URL能与哪些路由非常,在页面底部,它还会显示一个含有应用程序定义的所用路由列表,那样可以查看定义的哪位路由可以与当前URL相匹配。

安装教程如下:

视图=>其他窗口=>程序包管理控制台

公海赌船网址 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/。
  • 极少一些作品利用读书、参考、引用、抄袭、复制和粘贴等多种措施组成而成的,大部分为原创。
  • 如你喜欢,麻烦推荐一下;如您有新想法,欢迎指出,邮箱:2016177728@qq.com。
  • 可以转载该博客,但不可能不有名博客来源。

相关文章