局地人不想令人家知道本人文件的门道,例子引入

 
路由的着力是1个万分简单的算法,该算法基于一个由RouteCollection类和RouteBase类组成的简短抽象对象。能够行使八种主意来生成UWranglerL,但那几个办法都是调用RouteCollection.GetVirtualPath的3个重载方法而终结。RouteCollection.GetVirtulPath方法公有三个重载版本,上边包车型客车代码显示它们的点子签名:

§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 U奥德赛L schema—that is, the set of
UCR-VLs that are accepted and their mappings to controllers and actions.
下面大家来探视mvc中是怎么着定义路径的.

图片 1

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

 

2.3  路由定义

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

咱俩地点的看出的那段代码和系统自动生成的那段代码是同样的.

图片 2

 

§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.
早起的路由机制运营在框架的呼吁处理管道. 它的做事便是采纳进来的UHighlanderL,
并用它来获取3个能够处理请求的的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

路由配置主要有三个部分:

  • 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 USportageL is requested, the system invokes each of the IHttpModules
registered for the application. 当1个U奥迪Q5L被呼吁,
系统调用每一个在应用程序中早就登记的IHttpModules
.在那之中三个就是UrlRoutingModule

** 

The Order of Your Route Entries Is Important

If there’s one golden rule of routing, this is it: put
more-specific route entries before less-specific
ones.
假设有个路由布署的金子规则: 那么就是将与众差异路径放在一般路径的前边.
因为系统的妥帖由的算法是从最上方起始, 而不是找最符合的.

 

§8.2.2  Adding a Route Entry

私下认可的路由是很普通的, 如若你想要处理别的类其余U景逸SUVL, 你还索要做一些手脚.
作者来举个大约的事例, 比如大家想要用U奥迪Q5L /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

图片 3

 

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. 正像你眼下看到的, 参数能够置身{}里,
那里大家加2个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想要调用2个action方法,
它须求提供一个value给艺术的参数. 它获得value的3个地方正是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类型. 你会在第七章和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奥德赛L有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发来的一律UXC60L

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 被当作2个URubiconL模型, 就如二个平日的路由入口. 

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.

§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

图片 4

那般, 限制会很多, 有的人不想让外人精通本身文件的不二法门,
大概是那几个代表方法太为难了等等.

 

 
(1)开发职员调用像Html.ActionLink或Url.Action之类的法子,这么些点子反过来再调用RouteCollection.GetVirtual帕特h方法,并向它传递二个RequestContext对象、三个包涵值的字典以及用于选用生成U逍客L的路由名称(可选参数)。

2.11 How U福睿斯Ls Are Matched to
Routes(url怎样与路由相当)

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

译文:

2.1  WebForm URL与Route URL

图片 5

译文:

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

图片 6

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

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

能够回顾为如下流程图:

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

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

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

译文:下边的以身作则显示了来自.Globalasax文件的代码,该代码添加了贰个路由对象,该指标定义了三个名为action和花色称号的UCR-VL参数。具有钦赐情势的url被定向到名为分类.aspx的物理页面。

(1)路由集合通过RouteBase.GetVirtualPath方法遍历各样路由并走访:“能够变动给定参数的U帕JeroL吗”,那个历程看似于在路由与传播请求匹配时所运用的协作逻辑。

在窗口中输入:Install-Package
routedebugger

万一请求中缺少三个参数,则利用暗中认可值。因而,它们能够导致一条匹配您没有预料到的伏乞的路由。例如,若是您添加了以下方式:

译文:当路由拍卖U大切诺基L请求时,它尝试将请求的ULX570L与路由分外。将URL请求匹配到路由取决于以下原则:

8 参考文献

 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.

2.12 路由二义性

     (3)  便于输入;

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

译文:有时你必须处理包蕴1个可变多少的U陆风X8L段的URubiconL请求,在那之中。当你定义3个路由时,您可以钦点,假若一个UKoleosL的一部分比情势中有越来越多的段,那么额外的段被认为是最后一有个其他一有个别。要以那种措施处理额外的段,您可以用星号(*)标记最终二个参数。那被叫做二个不明的参数。八个带有全数参数的路由也将同盟不包涵最终三个参数的任何值的url。下边包车型大巴以身作则展现了三个很是未知数量的段的路由格局。

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

图片 7

2 路由概述(古板路由)

 

 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 }

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

译文:约束是经过应用正则表达式或选择实现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.

 图片 8

     UPAJERON(Uniform Resources
Name)代表统一能源名称,互连网上能源的称号;

图片 9图片 10

可能也能够应用NuGet很有益的装置RouteDebugger,在品种方面右键-“Manage
NuGet Packages”-“Online”输入”RouteDebugger”然后”Install”.

3 路由概述(性子路由)

只在同贰个化解方案中,存在五个以及上述同等控制器下的相同action,当ULacrosseL请求时,见面世二义性。

2.4 URL Patterns(URL模式)

A Physical File is Found that Matches
the ULacrosseL 帕特tern(找到与U奥迪Q3L形式匹配的大体文件)

2.2  ASP.NET 路由与 URL 重写

译文:日常地,在全局Global.asax文件中,您能够在一个叫做Application_Start
方法里添加路由。该方法确认保障当应用程序运维时,路由是能够采取的。它还使您能够在对应用程序举行单元测试时直接调用该方法。假诺您想在对应用程序举行单元测试时一直调用方法,那么注册路由的艺术必须是静态的(在Visual
Basic中是共享的),并且必须具备2个路由参数。

图片 11

  • 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.
  •  译文:您将它们拉长到路由集合的逐一。

二义性德姆o目录结构

 

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

译文:假如您通过创办从控制器基类派生的类来落到实处控制器的MVC约定,并给它们以“控制器”结尾的称号,那么你就不须要在MVC应用程序中手动添加路由了。预配置的路由将调用您在控制器类中达成的操作方法。

View
Code

   
调用GetRouteData方法会重临RouteData的三个实例。RouteData中带有了有关匹配请求的路由新闻。

 从内容上来看,个性路由的始末与观念路由大致,同样有路由UEvoqueL、路由值、控制器路由、路由约束和路由私下认可值等。鉴于篇幅限制,在那边就差不离的概述一下,不作详细阐释,中期有时间或许有意中人需求,再论述。

 如在VS二〇一一行使MVC模板创设项目时,自动生成类RouteConfig.

译文:带有形式能源的路由axd/pathInfo,被用来幸免Web能源文件的伸手,例如WebResource,axd或ScriptResource传递到控制器。对于IIS
7.0,不需求任何文件名称扩充。对于IIS
6.0,您必须添加.mvc文件扩充名到UPRADOL情势中,如上面包车型大巴例证:

2.5 Adding Routes to a Web Forms
Application(添加路由到WebForm运用程序)

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

 (2)路由体制查看须求的路由参数(即没有提供路由参数的暗中同意值),并保管提供的路由值字典为每贰个渴求的参数提供三个值,不然,UCR-VL生成程序就会立即停下,并回到空值。

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

 图片 12

译文:假若您提供3个IRouteConstraint对象,ASP.NET
路由通过调用IRouteConstraint对象的10分方法,
以此来检查参数值是还是不是行得通。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.)

9   版权

        ASP.NET 路由分裂于其余 U纳瓦拉L
重写方案。U奥迪Q3L 重写通过在将请求发送到网页在此以前实际更改 ULX570L
来处理传入请求。例如,三个行使 UHighlanderL 重写的应用程序大概会将 U奥迪Q3L 从 /Products/Widgets/ 更改为 /Products.aspx?id=4。其余,U锐界L 重写日常没有对号入座的 API
来创建基于形式的 U帕杰罗L。在 U奥迪Q3L 重写中,假如改动了 U奥迪Q7L
情势,则必须手动更新包含原始 U凯雷德L 的兼具超链接。由于
ASP.NET 路由得以从 U牧马人L 提取值,所以拍卖传入请求时不更改
U翼虎L。假使非得创设二个 ULANDL,则将参数值传递到为你生成 U讴歌RDXL
的办法中。若要更改 UTiggoL
情势,请在某地点变动该情势,您在应用程序中开创的依照该模式的富有链接将自行使用新方式。

2.9  Adding Constraints to
Routes(为路由添加封锁)

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.

(5)路由相当成!未来得以通过查看每三个路由参数,并尝试利用字典中的对应值填充相应参数,进而生成URubiconL。

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

视图=>其余窗口=>程序包管控台

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

      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.

     (2)  简短;

 译文:下边包车型地铁例证展示了在大局中创设暗中认可MVC路由的代码。asax文件,正如在Visual
Studio项目模板中定义的MVC应用程序。

  • 译文:您为某些路由提供的任何暗许值。
  • Any constraints that you have
    provided for a route.

  • 译文:您为路径所提供的其他约束。

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

  • 译文:是或不是定义了路由来处理与物理文件匹配的央浼。

        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.

     
(1)从命名角度,UCRUISERI标识财富且唯一,ULX570L标识财富地址
,U智跑N标识能源名称;

     
 译文:路由是一种被映射到有些处理程序的U途胜L格局。处理程序或许是3个物理文件,如在WebForms运用程序中的aspx文件。处理程序也或然是三个处理请求的类,如MVC应用程序中的控制器。要定义路由,您可以经过点名U普拉多L方式、处理程序和路径的称呼来创制路由类的实例。

译文:在MVC运用程序中,路由U安德拉L情势经常包括控制器和动作占位符。

图片 13

译文:U讴歌ZDXL方式或者包括文字值和变量占位符(称为U奥迪Q7L参数)。文字和占位符位于U瑞虎L的局地中,由斜杠(/)字符分隔。

 
译文:路线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.

译文:若是你想要路由拍卖全数请求,甚至指向文件的乞求,您能够透过安装RouteCollection对象的属性RouteExistingFiles为true, 
以此来覆盖默许值。当你将那一个值设置为true时,匹配定义格局的有着请求都由路由拍卖。

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.

 2.10 Scenarios When Routing Is Not
Applied(不应用路由时的场景)

图片 14

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

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

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

 Typical URL Patterns in MVC
Applications

图片 15

4.2 路由数据

自然, 你也足以团结下载RouteDebugger.dll,
引用到web项目中, 然后手动在web.config中出席

 先看看如下例子,你能一心理解啊?

     (5)
 应该是“可破解的”,用户可以因此移除U锐界L的末段,进而到达更高层次的新闻种类布局;

图片 16

图片 17

1.4 U哈弗L应负有特色

 定义:天性路由正是将路由UTiggoL定义在控制器上或控制器内的章程上,而不像守旧路由将路由U翼虎L定义在RouteConfig.cs中。相比如下

译文:当你定义三个路由时,您能够为三个参数钦定二个默许值。要是该参数的值没有包括在UXC60L中,则选用默许值。通过将dictionary对象分配给route类的默许属性,能够为路由安装暗中同意值。上面的例证显示了怎么通过行使MapPageRoute(字符串、字符串、字符串、布尔值、RouteValueDictionary)方法添加具有私下认可值的路由。

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

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.

1 @inherits System.Web.Mvc.WebViewPage
2 
3 <h2>RouteDebugger调试</h2>
1 public static void RegisterRoutes(RouteCollection routes)
2 {
3   routes.Ignore("{resource}.axd/{*pathInfo}");
4 }

译文:默许境况下,路由不处理映射到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.

      本解析基于1.2
USportageI、UKugaL和U哈弗N三者之间的关联图。

(2)假使3个路由能够应对下边包车型大巴难题(即匹配),那么它就会重回2个富含了UTucsonL的VirTual帕特hData实例以及其余匹配的信息。不然,它就回去空值,路由体制移向列表中的下3个路由。

   
 图片 18

2.8 Handling a Variable Number of Segments
in a U陆风X8L Pattern(在UOdysseyL方式中处理可变多少的段)

译文:下边包车型大巴示范呈现了什么样行使MapPageRoute方法创制一条路线,该路由限制了地区和年参数中得以蕴含的值。(在MVC应用程序中,您将利用map路由艺术。)

7 总结

译文:下表展现了私下认可的U宝马X3L方式,它显得了由私下认可路由拍卖的U福睿斯L请求的言传身教。

图片 19

设置教程如下:

译文:例如,假诺您添加了以下方式:
   Route 1 is set to
{controller}/{action}/{id}

2.6 Adding Routes to an MVC
Application

1 URI、URL与URN

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:

其次个重载接受七个参数,当中首个参数是路由名称。在路由集合中路由名称是绝无仅有的,也便是说,没有四个不等的路由具有同等的名号。当钦定了路由名称时,路由集合就不供给循环遍历每一个路由,相反,它能够马上找到内定名称的路由,并移向下面的步调(2)。若是找到的路由不能够匹配内定的参数,该方式就会回到空值,并且不再匹配别的路由。

图片 20

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.

View
Code

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.

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

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.

下表展现了实用的路由形式和与方式匹配的U奥迪Q5L请求示例。

 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 }
protected void Application_Start(object sender, EventArgs e)
{
    RegisterRoutes(RouteTable.Routes);
}

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

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

测试结果

译文:在Web
Forms应用程序中,您能够使用路由精选类的MapPageRoute(字符串、字符串、字符串)方法创立路由。MapPageRoute方法创立二个路由对象并将其添加到RouteCollection对象。您能够在传递给MapPageRoute方法的参数中钦点路由对象的习性。

图片 21图片 22

 3.1 U福特ExplorerL生成的高层系概述

事例引入

译文:除了通过UKoleosL中参数的数额来匹配U科雷傲L请求外,还是能够内定参数中的值满意一定的牢笼原则。就算一个URAV4L包括的值超出了路由的自律,那么该路由就不会被用于拍卖请求。您添加了一些封锁,以担保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.

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

控制器products.

3 路由生成U君越L

路由2永远不会处理请求,因为路由1率先被匹配,它总是匹配只怕在2号路径上中国人民解放军海军事工业程大学业作的央求。请求http://server/application/products/show/bikes似乎比赛路线2更紧密,但它是由路线1以下值:

注:该例子没有进入区域

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

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

图片 23

 

 (3)一些路由恐怕带有没有对应路由参数的默许值。如路由大概为category键提供暗中同意值“pastries”,可是cateory不是路由U兰德酷路泽L的2个参数,那种气象下,假诺用户传入的路由值字典为category提供了多个值,那么该值必须匹配category的默许值。

 

译文:在U奥迪Q5L形式中,通过将它们封装在括号(以及)中来定义占位符。您能够在五个段中定义几个占位符,然而必须用文字值分隔它们。例如,语言-国家/行动是一种有效的路子情势。然则,语言国家/action不是1个得力的方式,因为占位符之间从未文字值或分隔符。因而,路由无法控制将语言占位符的值与国家占位符的值分隔离。

图片 24图片 25

2.7 Setting Default Values for U福特ExplorerL
Parameters(为UXC90L参数设置暗中认可值)

译文:您还足以钦命路由不应有处理有些UENVISIONL请求。通过定义一条路由,并钦点StopRoutingHandler类应该用于拍卖该方式,从而幸免了处理有个别请求的路由。当2个StopRoutingHandler对象处理请求时,StopRoutingHandler对象会堵塞请求作为路由的其它附加处理。相反,请求是用作ASP.NET
页面来处理的,网络页面,Web服务,或其余ASP.NET端点。您能够动用 RouteCollection.Ignore方法。

     (6)  持久、不可能改变

译文:您能够经过包括常量来制止格局中的歧义,例如
annual/{report}/{year} and monthly/{report}/{year}/{month}。

 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                 

     
(2)从数学关系:U福睿斯I=U奥德赛L+U卡宴N+U汉兰达L∩UXC90N;很不难见到,ULANDL一定是UPRADOI,但UCRUISERI不肯定是U途锐L,同理,U帕杰罗N一定是U昂CoraI,但U福睿斯I不必然是U酷威N;

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

图片 26

途径2:报告/年,年暗中同意值。

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

 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 }

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.

译文:当接过到贰个请求时,它被路由到UrlRoutingModule对象,然后发送到MvcHandler
HTTP处理程序。MvcHandler
HTTP处理程序通过向UWranglerL中的控制器值添加后缀“控制器”来明确要调用哪个控制器,以显著控制器的类型名称,该控制器将处理请求。U路虎极光L中的操作值决定调用哪个操作方法。

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

 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 }

5 路由调节和测试

Routing Is Explicitly Disabled for a
U本田CR-VL Pattern(为U凯雷德L形式显式禁止使用路由)

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

/Controllers/NewFolder1/RouteDemo

译文:例如,一个包涵U卡宴L路径  /产品
的U途乐L映射到1个名为ProductsController的控制器。action参数中的值是调用的操作方法的名号。四个富含U君越L路径
  /产品/show
 的U陆风X8L会造成对ProductsController类的Showmethod的调用。

     
 常常状态下,U奥迪Q5I代表同意财富标识符(Uniform Resource
Identifier)。UPRADOI是标识了1个财富的字符串。从技术角度看,全体ULacrosseL都以U凯雷德I。W3C认为“U昂科雷L是贰个业余的定义,但它丰硕实惠:UEvoqueL是URAV4I的一种档次,它经过代表本人的重点走访机制来标识财富”,换句话说,UCRUISERI是某种能源的标识符,而UEnclaveL则为获得该能源提供了切实的新闻。

  • 多谢您的开卷,若有不足之处,欢迎指教,共同学习、共同进步。
  • 博主网址:http://www.cnblogs.com/wangjiming/。
  • 极少一些小说利用读书、参考、引用、抄袭、复制和粘贴等三种形式结合而成的,半数以上为原创。
  • 如您喜爱,麻烦推荐一下;如你有新想法,欢迎建议,邮箱:贰零壹肆177728@qq.com。
  • 能够转发该博客,但必须有名博客来源。

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(字符串、字符串、字符串)方法。

     UOdysseyI(Uniform Resource
Identifier)代表联合营源标识符,标识财富的字符串;

图片 27

测试结果

行动是show.

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

RouteDemoController

Index

 

路线1:报告/年/月,年和月私下认可值。

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

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

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.

     U中华VL (Uniform Resource
Locator)代表统一财富定位符,互联网上规范财富的地方;

 在这一章节,首要分析U奥德赛L绑定到控制器操作的平底细节,分析底层原理,明白ASP.NET请求管道。注意,近年来路由不仅仅只是ASP.NET
MVC的二个特征了,它已经超(Jing Chao)越这些限制,如ASP.NET Dynamic
Data。路由既不包涵MVC的当中级知识分子识,也不依靠于MVC。

 4.1 高层次请求的路由管道

 

     (2)ASP.NET
MVC中,平日地,UPRADOL映射并非映射到现实磁盘上的物理文件,那是基于ASP.NET路由脾气,重要有五个经过,即U库罗德L映射和U劲客L生成(接下去讲解)。在ASP.NET路由中,您能够定义U福睿斯L格局,该形式涵盖在处理U凯雷德L请求时接纳的值的占位符。在运维时,运用程序名称前边的UTiguanL部分根据你所定义的U奥德赛L情势分析为离散值。例如,在伸手http://server/application/Products/show/beverages时,路由分析器可以将值Products、show和beverages传递给请求的处理程序。相反,在一个不由URL路由管理的请求中,/Products/show/beverages片段将被解释为运用程序中的一个文件的路径。
  

译文:在少数意况下,即使在Web站点启用时,ASP.NET
路由也不处理请求。本有的讲述了一部分场所,当中路由不处理请求。

 6.2 Class
Reference( 路由涉及到的要害类)

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.

图片 28

View
Code

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

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

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

For example, a URL that includes the URL
path /Products is mapped to a controller named ProductsController. The value in the action parameter is the name of the action method that
is called. A URL that includes the URL path /Products/show would result in a call to the Showmethod of the ProductsController class.

/ query / { queryname } { * queryvalues
}

     
译文:你能够由此将路由对象添加到RouteTable类的静态路由属性中的格局将路由添加到应用程序中。路由属性是二个为应用程序存款和储蓄所有路由的路由对象。在MVC应用程序中,您平日不必要编写制定代码来添加路由。VS项目模板为MVC包涵了优先安插的UHavalL路由。这么些都以在MvcApplication类中定义的,被定义在Global.asac
文件中。

RouteConfig.cs

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  

 6.1  路由涉及的命名空间

 1.1 URI、URL和URN定义 

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

图片 29

4 路由绑定到操作

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

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.

 只要启用RouteDebugger,它就显得从(在地点栏中)当前呼吁U景逸SUVL中领到的路由数据。如此,能够在地点栏中输入各样U奇骏L,并查看输入的U途乐L能与哪些路由分外,在页面底部,它还会突显1个包罗应用程序定义的所用路由列表,那样能够查阅定义的哪位路由能够与当下U奥德赛L相匹配。

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

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:

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.

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

<add key="RouteDebugger:Enabled" value="true" />

 

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

1.3 对U安德拉I、U翼虎L和U君越N三者之间解析

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.

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.

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.

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

/Controllers/RouteDemo

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

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.

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

 
 路由三个首要职分:匹配传入的UOdysseyL请求和结构与一定路由对应的U揽胜L,总结之匹配UPAJEROL和组织U索罗德L。在生成U凯雷德L时,生成U讴歌ZDXL的意思应该首先与选拔用来生成U福睿斯L的路由相匹配,这样路由就足以在拍卖传入或传播的U卡宴L时改为完全的双向系统。原则上,开发人士应该提供一组路由值,以便路由系统从中选中第贰个能够匹配UCRUISERL的路由。

 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 }

【04】Professional Asp.net MVC 5

  3.2  USportageL生成详解

 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 }

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

   
如U瑞鹰L:{Controller}/{action}/{id}。当请求/albums/list/123传开时,该路由就会尝试匹配传入的请求,假使匹配成功,它就创立二个字典,个中带有了从U福睿斯L中分析出的音信。确切地讲,路由还会向Values字典中为UCR-VL中的每种路由参数添加三个键;对于价值观路由{Controller}/{action}/{id},Values字典中应有至少含有八个键,分别是Controller,action和id,倘使传入的U奥迪Q3L是对/albums/list/123的乞请,路由就会分析该请求的UOdysseyL,并为字典的键提供值。本例中,字典中“Controller”键的值为albums,”action”键的值为“list”,”id”键的值是“123”;对于特性路由MVC使用DataTokens字典来存款和储蓄更标准的音信,而不是操作名称字符串。具体来说,它富含1个操作描述符列表,这几个描述符直接指向路由匹配时可能利用的操作方法。对于控制器级别的性状路由,列表少校有持续一个操作。在方方面面MVC中都有利用的RequestContext的RouteData属性保存着外面路由值。

1.5  小结

 1.2 USportageI、U奇骏L和U翼虎N三者之间的关系图

id是bikes.

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

RouteConfig.cs

译文:当发出请求时,U纳瓦拉L被分析为一些和占位符,且变量值被提供给请求处理程序。这些进度看似于查询字符串中的数据被解析并传递给请求处理程序的方法。在那二种状态下,变量新闻都带有在U本田UR-VL中,并以键值对的款型传递给处理程序。对于查询字符串,键和值都在U劲客L中。对于路由,键是U奥迪Q7L情势中定义的占位符名称,在UWranglerL中唯有是值。

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

     
 注释:财富是叁个抽象概念,既能够指1个文件,也得以指方法调用的结果或服务器上的部分别的内容。

 
 使用RouteDebugger调节和测试,启用RouteDebugger后,它会用二个DebuggerRouteHandler替换全数路由处理程序,DebugRouteHandler截获全部传入的呼吁,并查询路由表中的每一个路由,以便在页面底部突显路由的确诊数据和参数。为使用RouteDebugger,只需在VS的Package
Manager Console窗口中选取NuGet安装即可,命令Install-Package
routedebugger.。RouteDebugger包在添加Route
Debugger程序集的同时。也在web.config文件的appSettings节点中添加2个安装,用来打开或禁止使用路由调节和测试。

路由2永远不会处理请求。第一条恐怕是对准每月报告的,而路由2恐怕是本着年度报告的。可是,路由第11中学的私下认可值意味着它将协作任何只怕用于路由2的伸手。

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.

相关文章