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

这样, 限制会繁多, 有的人不想让别人驾驭本身文件的途径,
可能是那几个代表方法太窘迫了等等.

 

注:本文是【ASP.NET Web
API连串教程
】的一有的,假诺您是率先次看本博客作品,请先看前边的内容。

 先看看如下例子,你能一心知晓啊?

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

You are given complete control of your U昂科威L schema—that is, the set of
UENVISIONLs 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
中.

 

4.1 Routing in ASP.NET Web API 4.1 ASP.NET Web API中的路由

正文引自:http://www.asp.net/web-api/overview/web-api-routing-and-actions/routing-in-aspnet-web-api

By Mike Wasson|February 11, 2012
作者:Mike Wasson | 日期:2012-2-11

This article describes how ASP.NET Web API routes HTTP requests to
controllers.
本小说描述ASP.NET Web API如何将HTTP央求路由到调控器。

If you are familiar with ASP.NET MVC, Web API routing is very similar to
MVC routing. The main difference is that Web API uses the HTTP method,
not the URI path, to select the action. You can also use MVC-style
routing in Web API. This article does not assume any knowledge of
ASP.NET MVC.
一旦你了解ASP.NET MVC,Web API路由与MVC路由相当好像。主要差距是Web
API使用HTTP方法而不是U福睿斯I路线来抉择动作。你也足以在Web
API中选取MVC风格的路由。本文不假诺你具有ASP.NET MVC的其他文化。

 1 using System;
 2 using System.Collections.Generic;
 3 using System.Linq;
 4 using System.Web;
 5 using System.Web.Mvc;
 6 using System.Web.Routing;
 7 
 8 namespace MVCDemo
 9 {
10     public class RouteConfig
11     {
12         public static void RegisterRoutes(RouteCollection routes)
13         {
14             routes.MapMvcAttributeRoutes();//特性路由
15 
16             routes.IgnoreRoute("{resource}.axd/{*pathInfo}");//忽略资源文件
17 
18             routes.MapRoute(
19                 name: "Default",//路由名,唯一
20                 url: "{controller}/{action}/{id}",//路由URL
21                 defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional },//路由URL默认值
22                 namespaces: new[] { "MVCDemo.Controllers" },//命名空间避免二义性
23                 constraints: new { id = @"^\d*$" }//约束
24 
25                 );
26         }
27     }
28 }

§8.2 Setting Up Routes

大家来探望路线的配备, 在global.asax.cs文件里

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

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

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

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

我们地点的见到的这段代码和连串自动生成的这段代码是完全一样的.

图片 3

 

§8.2.1  Understanding the Routing Mechanism

The routing mechanism runs early in the framework’s request processing
pipeline. Its job is to take an incoming U君越L and use it to obtain an
IHttpHandler object that will handle the request.
早起的路由机制运作在框架的乞请管理管道. 它的劳作正是使用进来的UPRADOL,
并用它来得到多个可见管理请求的的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猎豹CS6L 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

暗中认可的路由是很日常的, 倘使你想要管理其余类型的U奥德赛L, 你还索要做一些手脚.
小编来举个大致的例证, 举例大家想要用U翼虎L /Catalog来查看那几个类别的有着成品

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

我们得以用地点的这段代码来促成大家的目标. 它能够援救大家落实/Catalog
或许是 /Catalog?some=querystring, 不过 /Catalog/Anythingelse
那样的url是老大的.

 

URL Patterns Match the Path Portion of a URL

图片 4

 

Meet RouteValueDictionary

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

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

 

Take a Shortcut with MapRoute()

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

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

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

 

§8.2.3  Using Parameters

As you’ve seen several times already, parameters can be accepted via a
curly brace syntax. 正像你前边看到的, 参数能够放在{}里,
这里大家加二个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 });

诸如此类, 当访问的ULX570L有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发来的同等U途乐L

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

 

Matching Against Regular Expressions

为了保险参数是数字类型的, 大家运用那样的平整:

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

如此, route就可以匹配 /Articles/1 和 /Articles/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模型, 就如贰个普普通通的路由入口. 

Routing Tables 路由表

In ASP.NET Web API, a controller is a class that handles HTTP
requests. The public methods of the controller are called action
methods
or simply actions. When the Web API framework receives a
request, it routes the request to an action.
在ASP.NET Web
API中,一个控制器是拍卖HTTP须要的三个类。调控器的public方法称为动作方法action
methods
)或简称为动作action)。当Web
API框架接收到二个呼吁时,它将以此乞求路由到贰个动作。

To determine which action to invoke, the framework uses a routing table.
The Visual Studio project template for Web API creates a default
route:
为了鲜明调用哪三个动作,框架使用了一个路由表routing
table
)。Visual Studio中Web API的种类模板会创设多个默许路由:

routes.MapHttpRoute( 
    name: "API Default", 
    routeTemplate: "api/{controller}/{id}", 
    defaults: new { id = RouteParameter.Optional } 
);

This route is defined in the WebApiConfig.cs file, which is placed in
the App_Start directory:
那条路由是在WebApiConfig.cs文件中定义的,该公文位于App_Start目录(见图4-1):

图片 5

图4-1. 项目中的WebApiConfig.cs配置文件

For more information aboout the WebApiConfig class, see Configuring
ASP.NET Web
API
.
关于WebApiConfig类的越多音讯参谋“配置ASP.NET Web
API”(本课程连串的第10章 — 译者注)。

If you self-host Web API, you must set the routing table directly on the
HttpSelfHostConfiguration object. For more information, see
Self-Host a Web
API
.
比方要自托管(self-host )Web
API,你不可能不一向在HttpSelfHostConfiguration对象上安装路由表。越多信息仿照效法“自托管Web
API”(本课程连串的第8章 — 译者注)。

Each entry in the routing table contains a route template. The default
route template for Web API is “api/{controller}/{id}”. In this template,
“api” is a literal path segment, and {controller} and {id} are
placeholder variables.
路由表中的每一个条约都包含一个路由模板route template)。Web
API的暗许路由模板是“api/{controller}/{id}”。在那个模板中,“api”是一个文字式路线片段,而{controller}和{id}则是占位符变量。

When the Web API framework receives an HTTP request, it tries to match
the URI against one of the route templates in the routing table. If no
route matches, the client receives a 404 error. For example, the
following URIs match the default route:
当Web
API框架接收二个HTTP乞求时,它会筹划依据路由表中的二个路由模板来相称其U奥迪Q3I。假诺无路由十三分,客户端会接收到一个404(未找到)错误。比如,以下UOdysseyI与这几个暗许路由的相配:

  • /api/contacts
  • /api/contacts/1
  • /api/products/gizmo1

However, the following URI does not match, because it lacks the “api”
segment:
不过,以下U猎豹CS6I不相称,因为它贫乏“api”片段:

  • /contacts/1

Note: The reason for using “api” in the route is to avoid collisions
with ASP.NET MVC routing. That way, you can have “/contacts” go to an
MVC controller, and “/api/contacts” go to a Web API controller. Of
course, if you don’t like this convention, you can change the default
route table.
注:在路由中应用“api”的原由是为着防止与ASP.NET
MVC的路由冲突。通过这种艺术,能够用“/contacts”进入二个MVC调节器,而“/api/contacts”进入四个Web
API调节器。当然,如若您不爱好这种约定,能够修改这么些暗许路由表。

Once a matching route is found, Web API selects the controller and the
action:
假设找到了相配路由,Web API便会选择相应的支配和动作:

  • To find the controller, Web API adds “Controller” to the value of
    the {controller} variable.
    为了找到调节器,Web
    API会把“调控器”加到{controller}变量的值(意即,把U奥迪Q7I中的“调节器”作为{controller}变量的值
    — 译者注)。
  • To find the action, Web API looks at the HTTP method, and then looks
    for an action whose name begins with that HTTP method name. For
    example, with a GET request, Web API looks for an action that starts
    with “Get…”, such as “GetContact” or “GetAllContacts”. This
    convention applies only to GET, POST, PUT, and DELETE methods. You
    can enable other HTTP methods by using attributes on your
    controller. We’ll see an example of that later.
    为了找到动作,Web
    API会调查HTTP方法,然后找出一个名称以HTTP方法名初始的动作。举例,对于三个GET诉求,Web
    API会查找一个以“Get…”早先的动作,如“GetContact”或“GetAllContacts”等。这种约定仅使用于GET、POST、PUT和DELETE方法。通过把评释属性运用于调控器,你能够启用其余HTTP方法。前面会看出一个例证。
  • Other placeholder variables in the route template, such as {id}, are
    mapped to action parameters.
    路由模板中的其余占位变量,如{id},被映射成动作参数。

Let’s look at an example. Suppose that you define the following
controller:
让大家旁观三个事例。倘若你定义了以下调整器:

public class ProductsController : ApiController 
{ 
    public void GetAllProducts() { } 
    public IEnumerable<Product> GetProductById(int id) { } 
    public HttpResponseMessage DeleteProduct(int id){ } 
}

Here are some possible HTTP requests, along with the action that gets
invoked for each:
以下是局地恐怕的HTTP央求,及其将在被调用的动作:

HTTP Method
HTTP方法
URI Path
URI路径
Action
动作
Parameter
参数
GET api/products GetAllProducts (none)
(无)
GET api/products/4 GetProductById 4
DELETE api/products/4 DeleteProduct 4
POST api/products (no match)
(不匹配)

Notice that the {id} segment of the URI, if present, is mapped to the
id parameter of the action. In this example, the controller defines
two GET methods, one with an id parameter and one with no parameters.
注意,URI的{id}局地假设现身,会被映射到动作的id参数。在这些例子中,调控器定义了八个GET方法,当中二个富含id参数,而另五个不带参数。

Also, note that the POST request will fail, because the controller does
not define a “Post…” method.
其余要专注,POST伏乞是败退的,因为该调节器未定义“Post…”方法。

注:该例子未有到场区域

Routing Variations 路由变异

The previous section described the basic routing mechanism for ASP.NET
Web API. This section describes some variations.
上一节汇报了ASP.NET Web API基本的路由机制。本小节描述一些产生。

1 URI、URL与URN

HTTP Methods HTTP方法

Instead of using the naming convention for HTTP methods, you can
explicitly specify the HTTP method for an action by decorating the
action method with the HttpGet, HttpPut, HttpPost, or
HttpDelete attribute.
取代用于HTTP方法的命名约定,能够显著地为一个动作钦命HTTP方法,这是通过以HttpGetHttpPutHttpPostHttpDelete讲授属性对动作方法开始展览修饰来兑现的。

In the following example, the FindProduct method is mapped to GET
requests:
在下列示例中,FindProduct方法被映射到GET伏乞:

public class ProductsController : ApiController 
{ 
    [HttpGet] 
    public Product FindProduct(id) {} 
}

To allow multiple HTTP methods for an action, or to allow HTTP methods
other than GET, PUT, POST, and DELETE, use the AcceptVerbs
attribute, which takes a list of HTTP methods.
要允许一个动作有五个HTTP方法,或允许对GET、PUT、POST和DELETE以外的任何HTTP方法,需选用AcceptVerbs(接收谓词)表明属性,它以HTTP方法列表为参数。

public class ProductsController : ApiController 
{ 
    [AcceptVerbs("GET", "HEAD")]   // 指示该动作接收HTTP的GET和HEAD方法 — 译者注
    public Product FindProduct(id) { } 

    // WebDAV method
    // WebDAV方法(基于Web的分布式著作与版本控制的HTTP方法,是一个扩展的HTTP方法 — 译者注)
    [AcceptVerbs("MKCOL")]   // MKCOL是隶属于WebDAV的一个方法,它在URI指定的位置创建集合
    public void MakeCollection() { } 
}

 1.1 URI、URL和URN定义 

Routing by Action Name 通过动作名路由

With the default routing template, Web API uses the HTTP method to
select the action. However, you can also create a route where the action
name is included in the URI:
采纳暗中同意的路由模板,Web
API使用HTTP方法来挑选动作。但是,也能够制造在ULX570I中带有动作名的路由:

routes.MapHttpRoute( 
    name: "ActionApi", 
    routeTemplate: "api/{controller}/{action}/{id}", 
    defaults: new { id = RouteParameter.Optional } 
);

In this route template, the {action} parameter names the action method
on the controller. With this style of routing, use attributes to specify
the allowed HTTP methods. For example, suppose your controller has the
following method:
在那么些路由模板中,{action}参数命名了调控器上的动作方法。选取这种作风的路由,要求运用注明属性来指明所允许的HTTP方法。比如,假诺你的控制器有以下办法:

public class ProductsController : ApiController 
{ 
    [HttpGet] 
    public string Details(int id); 
}

In this case, a GET request for “api/products/details/1” would map to
the Details method. This style of routing is similar to ASP.NET MVC, and
may be appropriate for an RPC-style API.
在那几个例子中,八个对“api/products/details/1”的GET伏乞会映射到那一个Details方法。这种作风的路由类似于ASP.NET
MVC,而且说不定与RPC式的API相近似。

You can override the action name by using the ActionName attribute.
In the following example, there are two actions that map to
“api/products/thumbnail/id”. One supports GET and the other supports
POST:
能够由此选用ActionName讲解属性来掩盖动作名。在偏下例子中,有七个动作映射到“api/products/thumbnail/id”。三个接济GET,而另贰个帮衬POST:

public class ProductsController : ApiController 
{ 
    [HttpGet] 
    [ActionName("Thumbnail")] 
    public HttpResponseMessage GetThumbnailImage(int id); 

    [HttpPost] 
    [ActionName("Thumbnail")] 
    public void AddThumbnailImage(int id); 
}

     U中华VI(Uniform Resource
Identifier)代表联合财富标志符,标志能源的字符串;

Non-Actions 非动作

To prevent a method from getting invoked as an action, use the
NonAction attribute. This signals to the framework that the method
is not an action, even if it would otherwise match the routing rules.
为了防卫叁个措施被视作三个动作所诉求,要动用NonAction讲明属性。它对框架发出实信号:该情势不是三个动作,尽管它也许与路由法则相配。

// Not an action method.
// 不是一个动作方法
[NonAction] 
public string GetPrivateData() { ... }

     U大切诺基L (Uniform Resource
Locator)代表联合营源定位符,互联英特网正式财富的地方;

Further Reading 进一步读书

This topic provided a high-level view of routing. For more detail, see
Routing and Action
Selection
,
which describes exactly how the framework matches a URI to a route,
selects a controller, and then selects the action to invoke.
本论题提供了有关路由的全部概述。越多细节参见“路由与动作接纳”(本课程种类的下一小节

译者注),它纯粹地叙述了框架怎么样把USportageI相称到路由、怎么样抉择调控器、以及随后接纳动作举行调用。

看完此文假如感到全体收获,恳请给个推荐

     URAV4N(Uniform Resources
Name)代表联独财富名称,互联英特网财富的名号;

 1.2 U中华VI、USportageL和U奥迪Q3N三者之间的涉嫌图

图片 6

1.3 对U奥迪Q7I、U酷威L和U奥迪Q7N三者之间剖判

      本剖判基于1.2
UPAJEROI、U瑞虎L和U路虎极光N三者之间的关联图。

     
(1)从命名角度,U猎豹CS6I标记财富且唯一,UPAJEROL标记能源地址
,UGL450N标志财富名称;

     
(2)从数学关系:U本田UR-VI=U奥迪Q7L+ULacrosseN+U昂科威L∩ULacrosseN;很轻松见到,U奥德赛L一定是UKugaI,但U奥迪Q3I不料定是UEnclaveL,同理,U逍客N一定是U奥迪Q5I,但U卡宴I不必然是U奥迪Q3N;

1.4 U帕拉梅拉L应享有特色

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

     (2)  简短;

     (3)  便于输入;

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

     (5)
 应该是“可破解的”,用户能够透过移除U奥迪Q3L的末段,进而到达越来越高档案的次序的音讯种类布局;

     (6)  长久、无法改变

1.5  小结

     
 平时情况下,U智跑I代表同意能源标记符(Uniform Resource
Identifier)。UPAJEROI是标记了四个财富的字符串。从技艺角度看,所有U奥迪Q7L都是UGL450I。W3C感到“U索罗德L是贰个非正式的定义,但它丰盛管用:U本田UR-VL是UENCOREI的一种等级次序,它经过代表自个儿的显要走访机制来标志能源”,换句话说,UGL450I是某种财富的标志符,而U奥迪Q7L则为获取该财富提供了实际的音讯。

     
 注释:能源是贰个抽象概念,不只能够指一个文件,也能够指方法调用的结果或服务器上的一些任何剧情。

2 路由概述(古板路由)

2.1  WebForm URL与Route URL

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

   
 图片 7

     (2)ASP.NET
MVC中,平常地,UTucsonL映射并非映射到现实磁盘上的概略文件,那是基于ASP.NET路由脾性,首要有多少个进程,即UENVISIONL映射和U本田CR-VL生成(接下去讲解)。在ASP.NET路由中,您能够定义UHighlanderL情势,该方式涵盖在拍卖URubiconL哀告时接纳的值的占位符。在运维时,运用程序名称前面包车型大巴UENCOREL部分依据你所定义的UPAJEROL形式深入分析为离散值。比如,在伸手http://server/application/Products/show/beverages时,路由分析器可以将值Products、show和beverages传递给请求的处理程序。相反,在一个不由URL路由管理的请求中,/Products/show/beverages片段将被解释为运用程序中的一个文件的路径。
  

2.2  ASP.NET 路由与 URL 重写

        ASP.NET 路由分化于别的 U大切诺基L
重写方案。UXC90L 重写通过在将呼吁发送到网页在此以前实际更动 UPAJEROL
来拍卖传入央求。比如,二个使用 UPRADOL 重写的应用程序可能会将 UXC60L 从 /Products/Widgets/ 改换为 /Products.aspx?id=4。其它,UHavalL 重写日常未有相应的 API
来创立基于形式的 URubiconL。在 U昂科雷L 重写中,固然改换了 U安德拉L
方式,则必须手动更新包含原始 UMuranoL 的兼具超链接。由于
ASP.NET 路由得以从 U奥德赛L 提取值,所以拍卖传入乞求时不改动ULacrosseL。若是非得制造贰个 U陆风X8L,则将参数值传递到为你生成 UENVISIONL
的方法中。若要改造 UCR-VL
情势,请在某地方变动该格局,您在应用程序中开创的依靠该形式的富有链接将活动使用新形式。

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.

     
 译文:路由是一种被映射到有些管理程序的UCRUISERL形式。管理程序恐怕是七个概略文件,如在WebForms运用程序中的aspx文件。管理程序也只怕是二个拍卖恳求的类,如MVC应用程序中的调整器。要定义路由,您能够由此点名U本田UR-VL情势、管理程序和路径的名号来成立路由类的实例。

      You add the route to the
application by adding the Route object to the static Routes property of
the RouteTable class. The Routes property is a RouteCollection object
that stores all the routes for the application.You typically do not have
to write code to add routes in an MVC application. Visual Studio project
templates for MVC include preconfigured URL routes. These are defined in
the MvcApplication class, which is defined in the
Global.asax file.

     
译文:你能够通过将路由对象加多到RouteTable类的静态路由属性中的形式将路由增添到应用程序中。路由属性是贰个为应用程序存款和储蓄全体路由的路由对象。在MVC应用程序中,您平日没有供给编写制定代码来增添路由。VS项目模板为MVC包罗了前期陈设的U中华VL路由。这个都以在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福特ExplorerL形式大概包涵文字值和变量占位符(称为U奇骏L参数)。文字和占位符位于U兰德卡宴L的有个别中,由斜杠(/)字符分隔。

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.

译文:当发出央浼时,ULANDL被剖析为部分和占位符,且变量值被提供给须求管理程序。这几个进度看似于查询字符串中的数据被分析并传递给央求管理程序的主意。在那三种情景下,变量音信都富含在U智跑L中,并以键值对的样式传递给处理程序。对于查询字符串,键和值都在UEscortL中。对于路由,键是U君越L情势中定义的占位符名称,在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.

译文:在UENVISIONL情势中,通过将它们封装在括号(以及)中来定义占位符。您能够在贰个段中定义多少个占位符,可是必须用文字值分隔它们。比如,语言-国家/行动是一种有效的门路格局。但是,语言国家/action不是三个可行的格局,因为占位符之间向来不文字值或分隔符。因而,路由无法调整将语言占位符的值与国家占位符的值分隔开分离。

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

下表展现了有效的路由形式和与形式相配的U兰德揽胜极光L须要示例。

图片 8

 Typical URL Patterns in MVC
Applications

译文:MVC运用程序中的出色格局

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

译文:在MVC运用程序中,路由UHighlanderL情势平常包蕴调控器和动作占位符。

When a request is received, it is routed
to the UrlRoutingModule object and then to the MvcHandler HTTP handler.
The MvcHandler HTTP handler determines which controller to invoke by
adding the suffix “Controller” to the controller value in the URL to
determine the type name of the controller that will handle the request.
The action value in the URL determines which action method to
call.

译文:当接到到四个伸手时,它被路由到UrlRoutingModule对象,然后发送到MvcHandler
HTTP管理程序。MvcHandler
HTTP管理程序通过向U奥德赛L中的调节器值增多后缀“调整器”来鲜明要调用哪个调整器,以显著调节器的品种名称,该调控器将拍卖伏乞。UTiguanL中的操作值决定调用哪个操作方法。

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.

译文:比方,一个包涵U奥迪Q5L路线  /产品
的ULacrosseL映射到四个名称叫ProductsController的调节器。action参数中的值是调用的操作方法的名号。多个富含U冠道L路径  /产品/show
 的UTiggoL会形成对ProductsController类的Showmethod的调用。

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

译文:下表显示了默许的U奥迪Q7L方式,它展现了由暗许路由拍卖的UEvoqueL必要的亲自过问。

 图片 9

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文件扩张名到U奥迪Q3L方式中,如下边包车型客车事例:

 图片 10

 如在VS二零一三采纳MVC模板创建项目时,自动生成类RouteConfig.

图片 11

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和类型称号的UKugaL参数。具有钦赐方式的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(为U奥迪R18L参数设置私下认可值)

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.

译文:当您定义一个路由时,您可感觉一个参数内定二个暗许值。假如该参数的值未有包含在UTucsonL中,则利用暗许值。通过将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.

图片 12

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 U大切诺基L Pattern(在U奥迪Q5L方式中拍卖可变多少的段)

Sometimes you have to handle URL requests
that contain a variable number of URL segments. When you define a route,
you can specify that if a URL has more segments than there are in the
pattern, the extra segments are considered to be part of the last
segment. To handle additional segments in this manner you mark the last
parameter with an asterisk (*). This is referred to
as a catch-all parameter. A route with a
catch-all parameter will also match URLs that do not contain any values
for the last parameter. The following example shows a route pattern that
matches an unknown number of segments.

译文:不时你必须管理包涵贰个可变多少的UTucsonL段的U昂CoraL央求,当中。当您定义叁个路由时,您能够钦赐,若是贰个UHavalL的片段比情势中有愈来愈多的段,那么额外的段被认为是终极一片段的一片段。要以这种方法处理额外的段,您可以用星号(*)标志最终一个参数。那被称作二个含糊的参数。多个包含全数参数的路由也将非常不分包最后二个参数的任何值的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奥迪Q5L诉求时,示例中所示的路由定义发生了下表中列出的结果。

图片 13

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.

译文:除了通过U福特ExplorerL中参数的数额来相称UCR-VL要求外,还足以钦命参数中的值满意特定的封锁原则。假设二个UENCOREL包罗的值大于了路由的约束,那么该路由就不会被用于拍卖诉求。您增加了一部分封锁,以担保U翼虎L参数包蕴在你的应用程序海南中华工程公司作的值。
Constraints are defined by using regular
expressions or by using objects that implement the IRouteConstraint
interface. When you add the route definition to the Routes collection,
you add constraints by creating a RouteValueDictionary object that
contains the verification test. The key in the dictionary identifies the
parameter that the constraint applies to. The value in the dictionary
can be either a string that represents a regular expression or an object
that implements the IRouteConstraint interface.

译文:约束是因而选拔正则表明式或选择完结IRouteConstraint接口的目的来定义的。当将路由定义增加到路由集结时,通过创建一个蕴涵验证测验的RouteValueDictionary对象来增进约束。字典中的键标记约束应用到的参数。字典中的值可以是表示正则表明式的字符串,也足以是兑现IRouteConstraint接口的对象。
If you provide a string, routing treats
the string as a regular expression and checks whether the parameter
value is valid by calling the IsMatch method of the Regex class. The
regular expression is always treated as case-insensitive. For more
information, see .NET Framework Regular Expressions.

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

图片 14

 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 UGL450L Pattern(找到与UENVISIONL情势相配的大要文件)

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
UENCOREL 帕特tern(为UOdysseyL方式显式禁止使用路由)

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  

译文:您还足以钦点路由不应有处理某个USportageL须求。通过定义一条路由,并内定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怎样与路由极度)

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:

译文:当路由拍卖UCRUISERL央浼时,它尝试将呼吁的UHeritage EVL与路由卓殊。将U陆风X8L须要相配到路由取决于以下原则:

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

假如UENVISIONL不包容在RouteTable集结中定义的其他路由对象,ASP.NET路由不管理需要。相反,管理被传送给二个ASP.NET
Page ,Web服务,或别的ASP.NET端点。

2.12 路由二义性

只在同一个化解方案中,存在七个以及上述同等调节器下的一样action,当U奥迪Q5L乞求时,会见世二义性。

二义性德姆o目录结构

图片 15

RouteConfig.cs

图片 16图片 17

 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

图片 18图片 19

 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

图片 20图片 21

 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

测验结果

图片 22

3 路由概述(性子路由)

 性格路由是在ASP.NET MVC
5中新扩张的,古板路由ASP.NET MVC 第11中学就有了。

 从内容上来看,个性路由的从头到尾的经过与思想路由差不离,同样有路由UWranglerL、路由值、调整器路由、路由约束和路由暗中同意值等。鉴于篇幅限制,在此地就大约的概述一下,不作详细演说,早先时期有时间也许有意中人必要,再论述。

 定义:个性路由就是将路由U奥迪TT RSL定义在调控器上或调整器内的秘籍上,而不像守旧路由将路由U福睿斯L定义在RouteConfig.cs中。比较方下

图片 23

 

图片 24

3 路由生成U牧马人L

 
 路由三个重要义务:相配传入的UXC60L央求和组织与一定路由对应的U奥迪Q5L,归纳之相称UEvoqueL和结构UPAJEROL。在生成U途乐L时,生成ULX570L的情致应该首先与选拔用来生成U牧马人L的路由相匹配,这样路由就能够在拍卖传入或传播的U福睿斯L时成为全部的双向系统。原则上,开采人士应该提供一组路由值,以便路由系统从中选中第一个能够相配UTiggoL的路由。

 3.1 UKoleosL生成的高层系概述

 
路由的着力是一个非常轻巧的算法,该算法基于二个由RouteCollection类和RouteBase类组成的简约抽象对象。可以行使各种艺术来生成UPAJEROL,但这几个点子都以调用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方法遍历各类路由并走访:“能够生成给定参数的UOdysseyL吗”,这几个进程看似于在路由与传播需求匹配时所采取的合作逻辑。

(2)假诺四个路由能够答应上边的标题(即相称),那么它就能回到一个分包了ULX570L的VirTualPathData实例以及别的相称的新闻。不然,它就重回空值,路由体制移向列表中的下一个路由。

其次个重载接受三个参数,当中第一个参数是路由名称。在路由群集中路由名称是头一无二的,约等于说,未有多个不等的路由具备同等的名号。当内定了路由名称时,路由集合就无需循环遍历每种路由,相反,它能够立刻找到钦命名称的路由,并移向上面包车型地铁手续(2)。假若找到的路由不可能匹配钦赐的参数,该办法就能回来空值,并且不再相称别的路由。

  3.2  U牧马人L生成详解

 
(1)开采人士调用像Html.ActionLink或Url.Action之类的点子,这一个办法反过来再调用RouteCollection.GetVirtualPath方法,并向它传递一个RequestContext对象、贰个分包值的字典以及用于选取生成U奥德赛L的路由名称(可选参数)。

 (2)路由体制查看供给的路由参数(即未有提供路由参数的暗许值),并保险提供的路由值字典为每二个须求的参数提供贰个值,不然,U本田CR-VL生成程序就能立即结束,并重返空值。

 (3)一些路由可能包括未有对应路由参数的暗中同意值。如路由大概为category键提供暗中同意值“pastries”,不过cateory不是路由ULANDL的多少个参数,这种情景下,假如用户传入的路由值字典为category提供了三个值,那么该值必须相配category的暗许值。

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

(5)路由相当成!将来能够透过查阅每八个路由参数,并尝试选取字典中的对应值填充相应参数,进而生成UENCOREL。

能够概括为如下流程图:

图片 25

 

4 路由绑定到操作

 在这一章节,首要剖判U帕杰罗L绑定到调整器操作的平内部原因节,深入分析底层原理,精晓ASP.NET乞请管道。注意,近来路由不仅只是ASP.NET
MVC的二个特色了,它曾经超(英文名:jīng chāo)越这几个范围,如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中富含了关于相称须要的路由音信。

   
如U大切诺基L:{Controller}/{action}/{id}。当央求/albums/list/123扩散时,该路由就能够尝试匹配传入的呼吁,即便同盟成功,它就创制一个字典,个中储存了从U景逸SUVL中分析出的新闻。确切地讲,路由还会向Values字典中为UMuranoL中的每一个路由参数加多三个键;对于守旧路由{Controller}/{action}/{id},Values字典中应当至少含有多少个键,分别是Controller,action和id,假设传入的U帕杰罗L是对/albums/list/123的央求,路由就能够深入分析该央浼的U奥迪Q5L,并为字典的键提供值。本例中,字典中“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,它就显得从(在地点栏中)当前恳请URubiconL中领到的路由数据。如此,能够在地方栏中输入各类U哈弗L,并查看输入的UENCOREL能与哪些路由特别,在页面底部,它还有只怕会展现一个含有应用程序定义的所用路由列表,那样能够查阅定义的哪个路由能够与当前U猎豹CS6L相相称。

安装教程如下:

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

图片 26

在窗口中输入:Install-Package
routedebugger

图片 27

照旧也可以利用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>

 

图片 28

6 与路由有关的主要命名空间和类

 6.1  路由涉及的命名空间

图片 29

 6.2 Class
Reference( 路由涉及到的第一类)

图片 30

 

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/。
  • 极少一些小说利用读书、参照他事他说加以侦察、引用、抄袭、复制和粘贴等二种方法结合而成的,大多数为原创。
  • 如您疼爱,麻烦推荐一下;如你有新主见,迎接提议,邮箱:二零一四177728@qq.com。
  • 能够转发该博客,但必须盛名博客来源。

相关文章