注:本文是【ASP.NET Web API系列教程】的一部分,如果您是第一次看本博客文章,請先看前面的內容。
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方法而不是URI路徑來選擇動作。你也可以在Web API中使用MVC風格的路由。本文不假設你具備ASP.NET MVC的任何知識。
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):

圖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請求時,它會試圖根據路由表中的一個路由模板來匹配其URI。如果無路由匹配,客戶端會接收到一個404(未找到)錯誤。例如,以下URI與這個默認路由的匹配:
- /api/contacts
- /api/contacts/1
- /api/products/gizmo1
However, the following URI does not match, because it lacks the "api" segment:
然而,以下URI不匹配,因為它缺少“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}變量的值(意即,把URI中的“控制器”作為{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基本的路由機制。本小節描述一些變異。
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方法,這是通過以HttpGet、HttpPut、HttpPost或HttpDelete注解屬性對動作方法進行修飾來實現的。
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() { } }
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方法來選擇動作。然而,也可以創建在URI中包含動作名的路由:
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); }
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() { ... }
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.
本論題提供了關於路由的總體概述。更多細節參見“路由與動作選擇”(本教程系列的下一小節 — 譯者注),它精確地描述了框架如何把URI匹配到路由、如何選擇控制器、以及隨后選擇動作進行調用。
看完此文如果覺得有所收獲,懇請給個推薦