ASP. 2 Lesson--web API Routing

Source: Internet
Author: User

ASP. NET Web API navigation

ASP. First lesson--Getting Started http://www.cnblogs.com/aehyok/p/3432158.html

ASP. The second lesson--crud operation Http://www.cnblogs.com/aehyok/p/3434578.html

ASP. NET Web API lesson three ——. NET client invoke Web API http://www.cnblogs.com/aehyok/p/3439698.html

ASP. Fourth lesson--httpclient Message Processor http://www.cnblogs.com/aehyok/p/3441915.html

Objective

This article describes how the ASP. NET WEB API routes HTTP requests to a controller.

If you are familiar with the route of the ASP. NET Mvc,web API, the route to ASP. NET MVC is very similar. The main difference is that the Web API uses an HTTP method instead of a URI path to select action. You can also use MVC-style routing in the Web API. This article does not need to have any basis for ASP.

Routing Tables Routing Table

In the ASP. NET Web API, a controller is a class that handles HTTP requests, and the public method of the controller is called an action method or a simple aciton. When the Web API receives a request, it routes the request to an action.

To make sure that action is invoked, the framework uses a routing table. The project template for the Web API in Visual Studio creates a default route:

            Config. Routes.maphttproute (                name: "Defaultapi",                routetemplate: "Api/{controller}/{id}",                defaults:new {id = Routeparameter.optional}            );

This route is defined in the WebApiConfig.cs file, which is located in the App_start directory.

For more information about the Webapiconfig class, see "Configuring the ASP. NET Web API" (temporarily not implemented)

If you want to host your Own (self-host) Web API, you must set up the routing table directly on the httpselfhostconfiguration object. For more information, see "Self-hosted web APIs". (temporarily not implemented)

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

When the Web API framework receives an HTTP request, it attempts to match its URI against a route template in the routing table. If there is no route match, the client receives a 404 (not found) error. For example, the following URI matches this default route:

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

However, the following URI does not match because it lacks an "API" fragment:

    • /contacts/1

The reason for using "API" in routing is to avoid routing conflicts with ASP. In this way, "/contacts" can be used to enter an MVC controller, while "/api/contacts" enters a Web API controller. Of course, if you don't like the Convention, you can also modify the default routing table.

Once a matching route is found, the Web API chooses the appropriate controller and action.

1. In order to find the Controller,web API, the "controller" is added to the value of the {controllers} variable.

2. To find the Action,web API, look for the HTTP method, and then look for a method with the name beginning with the HTTP method name. For example, for a GET request, the Web API looks for an action that begins with "Get ...", such as "getcontact" or "getallcontacts". This Convention applies only to get, POST, put, and delete methods. By using attributes on your controller, you can enable other HTTP methods. We'll see an example later.

3. Other placeholder variables in the routing template, such as {ID}, will be mapped to the action's parameters.

Let's look at a simple example, assuming you have defined the following controllers:

public class Productscontroller:apicontroller {public     void Getallproducts () {} public     ienumerable<product > getproductbyid (int id) {} public     httpresponsemessage deleteproduct (int id) {}}

Here are some possible HTTP requests, and each action to be called:

Note that if the {ID} fragment in the URI appears, it will be mapped to the ID parameter of the action. In this example, the controller defines two get methods, one with the ID parameter and one without the ID parameter.

Also note that the POST request is unsuccessful because the controller does not define a "Post ..." method.

Routing Variations Routing Changes

The previous section describes the basic routing mechanism for the ASP. This section describes some of the changes.

HTTP method

Instead of naming conventions that use HTTP methods, you can explicitly specify an HTTP method for an action by decorating the action method with the HttpGet, HttpPost, Httpput, or Httpdelete properties.

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

public class Productscontroller:apicontroller {     [httpget] public     Product findproduct (ID) {}}

Allow an action to correspond to multiple HTTP methods, or allow HTTP methods other than GET, Put, Post, and Delete methods, using the acceptverbs annotation property, which takes an HTTP method list as an argument.

public class productscontroller:apicontroller{    [Acceptverbs ("GET", "HEAD")] public    Product findproduct (ID) { }    //WebDAV method    [Acceptverbs ("Mkcol")] public    void Makecollection () {}}

The first method: Indicates that the action receives HTTP GET and head methods (this head has not been tested)

The second method: The WebDAV method (Web-based distributed works and version-controlled HTTP method, is an extended HTTP method

Mkcol is a method that is subordinate to WebDAV, which creates a collection at the location specified by the URI (WebDAV has not seen it)

Route by Action name

In the default routing template, this Web API uses the HTTP method to select action. However, you can also create a route with an action name in the URI:

Routes. Maphttproute (     name: "Actionapi",     routetemplate: "Api/{controller}/{action}/{id}",     defaults:new {id = Routeparameter.optional});

In this routing template, the {action} parameter names the action method on the controller. With this style of routing, you need to use annotation properties to indicate which HTTP method is allowed. For example, suppose your controller already has the following methods:

public class Productscontroller:apicontroller {     [httpget] public     string Details (int id);}

In this case, a GET request "API/PRODUCTS/DETAILS/1" will be mapped to this Details method. This style of routing is similar to ASP. NET MVC, and may be close to the RPC-style API. (RPC style is not very understanding, have not checked the information)

You can also override the action name by using the actionname annotation property. In the following example, there are two actions mapped to "api/products/thumbnail/id". One supports get, while the other supports 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 being requested as an action, you can use the nonaction annotation property. It signals the frame: This method is not an action, even if it may match the routing rule.

Summarize

This lesson is primarily about providing a holistic overview of routing. The next lesson will describe exactly how the framework matches URLs to routes, how to select Controllers, and select actions to invoke.

This article refers to the link: http://www.asp.net/web-api/overview/web-api-routing-and-actions/routing-in-aspnet-web-api

ASP. 2 Lesson--web API Routing

Related Article

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.