Web API Series Tutorial 2.1-asp.net the routing mechanism in the Web API

Source: Internet
Author: User

This article describes how the ASP. NET Web API sends (routes) HTTP requests to the controller.

Note: If you are familiar with ASP. NET MVC, you will find that the Web API routing is very similar to the MVC route. The main difference is that the Web API uses the HTTP method to select an action (action) instead of a URI path. You can also use MVC-style routing in the Web API. This article does not require any knowledge of ASP.

routing Table

In the ASP. NET Web API, the controller is a class that handles HTTP requests. Public methods in the controller are called action methods or simple actions. When the Web API framework receives a request, it routes the request to the appropriate action.

To determine which action should be executed, the framework uses the routing table that will be explained in this section. The Web API project template for Visual Studio creates a default routing table:

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

This route is defined in the WepApiConfig.cs file in the App_start directory.

Each record in the routing table contains a route template. The default route template for the Web API is "Api/{controller}/{id}". In this template, "API" is a literal path field, and {controller} and {ID} are placeholder variables.

When the Web API framework receives an HTTP request, it tries to match the URI to one of the routing templates in the routing table. If no route is matched, the client receives a 404 error. For example, the following URI will match to the default route:
1,/api/contacts
2,/API/CONTACTS/1
3,/api/products/gizmo1
However, the following URI does not match, because it lacks an "API" field.
/contacts/1
Note: The reason for using the API in routing is to avoid routing conflicts with ASP. That is, you can use "/contacts" to match the route to MVC, using "api/contacts" to match the route to the Web API. Of course, if you don't like the Convention, you can also modify the default routing table.

Once a route is matched, the Web API chooses the appropriate controller and action:
1, in order to locate the controller, the WEB API adds "controller" to the {controllers} variable.
2, in order to find the action, the Web API iterates through the HTTP method and looks for an action whose name begins with the name of the HTTP method. For example, with a GET request, the Web API looks for actions that begin with "Get ....", such as "getcontact" or "getallcontacts". This approach only applies to get, POST, put, and delete methods. You can enable other HTTP methods by using properties in your controller. You will see a sample later (hyperlink to section III of this chapter ...).
3, other placeholder variables for the routing template, such as {ID}, are mapped to the parameters of the action.

Let's take a look at an example. Assume that you have defined the following controller:

publicclass ProductsController : ApiController{    publicvoidGetAllProducts() { }    publicGetProductById(int id) { }    publicDeleteProduct(int id){ }}

Here are some possible HTTP requests, along with the corresponding actions to get executed:

HTTP Method URI Path Action Parameter
GET Api/products Getallproducts (none)
GET Api/products/4 Getproductbyid 4
DELETE Api/products/4 Deleteproduct 4
POST Api/products (no match)

Note that the {ID} field of the URI, if present, is mapped to the ID parameter of the action. In this example, the controller defines two get methods, one of which contains the ID parameter, and the other does not contain the ID parameter.

Similarly, notice that the POST request fails because the "post ..." method is not defined in the controller.

Route skew (Routing variations)

The previous section describes the basic routing mechanism for the ASP. This section will begin to describe some changes.

HTTP method

In addition to using the naming conventions for these HTTP methods, you can specifically set the HTTP method for each action by assigning these actions with the HttpGet, Httpput, HttpPost, or Httpdelete attributes.

In the following example, the Findproduct method is mapped to a GET request:

publicclass ProductsController : ApiController{    [HttpGet]    publicFindProduct(id) {}}

To allow an action to support multiple HTTP methods, or to support HTTP methods other than GET, PUT, post, and delete, you can use the Acceptverbs property, which takes a list of HTTP methods as parameters.

publicclass ProductsController : ApiController{    [AcceptVerbs("GET""HEAD")]    publicFindProduct(id) { }    // WebDAV method    [AcceptVerbs("MKCOL")]    publicvoidMakeCollection() { }}
route through the action name

With the default routing template, the Web API uses the HTTP method to select the action. However, you can also create a routing table that contains the action name in the URI.

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

In this routing template, the {action} parameter names an action method in the controller. In this style of routing, you should use attributes to specify the allowed HTTP methods. For example, suppose your controller has the following methods:

publicclass ProductsController : ApiController{    [HttpGet]    publicstringDetails(int id);}

In this case, a GET request for "API/PRODUCTS/DETAILS/1" is mapped to the details method. This style of routing is close to ASP. NET MVC and may be appropriate for RPC-style APIs.

You can override the action name by using the ActionName property. In the following example, there are two actions that are mapped to "api/products/thumbnail/id". One supports get and the other supports post:

publicclass ProductsController : ApiController{    [HttpGet]    [ActionName("Thumbnail")]    publicGetThumbnailImage(int id);    [HttpPost]    [ActionName("Thumbnail")]    publicvoidAddThumbnailImage(int id);}
no Action (non-actions)

To prevent a method from being executed as an action, you can use the Nonaction property. The framework indicates that the method is not an action, even though it may match the routing rule.

// Not an action method.[NonAction]  ... }

Web API Series Tutorial 2.1-asp.net the routing mechanism in the Web API

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.