Web api-Routing (i)

Source: Internet
Author: User

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

If you are familiar with ASP. NET Mvc,web API Routing and MVC routing are very similar, the main difference is that the Web API uses the HTTP method instead of the URI path to select action. You can also use MVC-style routing in Webapi, an article that does not discuss any knowledge of MVC.

Routing table:

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

The WEB API framework uses a route table to determine which action is called. VS's Web API project template creates a default routing template:

routes. Maphttproute (    "API Default",    "api/{controller}/{ ID}",    new {id = routeparameter.optional});

This routing template is defined in the WebApiConfig.cs file in the App_start directory. More information on Webapiconfig can be seen at: Configuring ASP. NET Web API.

If you are using a self-hosted (self-host) Web API, you must set up the routing table by httpselfhostconfiguration yourself, for more information refer to: Self-host a Web API.

Each entry in the routing table contains a template, and the default Web API routing template is "Api/{controller}/{id}". In this template, "API" is a plain text path segment, {controller} and {ID} are placeholders (parameter variables). When the Web API framework receives a request, it attempts to match the URI to the entry in the routing table (the route template) and returns a 404 error if there are no route entries that can be matched, such as the following three URIs that match the default route template.

/api/contacts

/api/contacts/1

/api/products/gizmo1

But/CONTACTS/1 this will not match because the "API" segment is missing.

Note : The Web API routing template starts with "API" to avoid conflicts with MVC's routing templates, so you can use the "/contacts" uri to route to an MVC controller, using "Api/contacts" Routed to a Web API controller. Of course, if you don't like it, you can modify the default routing template.

Once a matching route is found, theWeb API chooses the controller and action :

--to find the controller, Web API adds "controller" to the value of the {controller} variable.

--Match the Action,web API to view this HTTP method, for example: if it is a get method, look for a method in the controller that starts with GET, and this query starts with an HTTP request in the way that the action is only suitable for GET, POST, PUT, and DELETE mode HTTP request??? , you can specify how the action can match the HTTP request and allow other HTTP requests by adding a method that identifies the property to the action.

--The placeholder variables in the other routing templates, such as {ID}, are mapped to an action parameter.

Let's look at an example: Define a controller as follows

 Public class productscontroller:apicontroller{    publicvoid  getallproducts () {}      Public ienumerable< Product> Getproductbyid (int  ID) {}    public httpresponsemessage deleteproduct (int  ID) {}}

The following table shows the action that is called by the different URIs

HTTP Method

URI Path

Action

Parameters

GET

Api/products

Getallproducts

No

GET

Api/products/4

Getproductbyid

4

DELETE

Api/products/4

Deleteproduct

4

POST

Api/products

There's no matching action

Note: The {ID} segment here, if the value of {ID} is specified, invokes the action method Getproductbyid with the ID parameter.

Because there is no Aciton method defined at the beginning of the post, a matching action is not found for the Post method request.

Routing extension

-- using the HTTP Methods identity attribute : In addition to defining an action method that starts with an HTTP request, we can use HttpGet, Httpput, HttpPost, or Httpdelete identity property to specify a ACTI The on method matches the HTTP request method (as with the method name that starts with the HTTP request), for example, the following method can match the HTTP request in the GET request.

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

You can use Accptverbs to identify attributes if an action method needs to match multiple HTTP request modes, or if you need to match a request other than Get,post,put,delete request. For example, the Findproduct method can match both GET and head requests.

 public  class   productscontroller:apicontroller{[Acceptverbs (  " get  , "  head   )]    Product findproduct (id) {}  //   WebDAV method  [Acceptverbs ( " Span style= "color: #800000;" >mkcol   )]  public  void   Makecollection () {}} 

--Using MVC-style routing

To define a route template:

routes. Maphttproute (    "actionapi",    "api/{controller}/{ Action}/{id}",    new {id = routeparameter.optional});

In this route template, the {action} parameter specifies the name of the action in the controller, and using this style of routing requires that the identity attribute be used to specify how the action allows matching HTTP requests, such as: [HttpGet], [HttpPost] such as identity attributes.

 Public class productscontroller:apicontroller{    [httpget]    publicstring Details (int  ID);}

In the example above, a GET request for "API/PRODUCTS/DETAILS/1" will be mapped to the details method. This style is much like MVC and may be more suitable for use in a Rpc-style API.

-- Use the ActionName property to define an alias for the action:

 public  class   productscontroller:apicontroller{[HttpGet] [ActionName (  " thumbnail  "  )]  public  httpresponsemessage getthumbnailimage (int   ID);    [HttpPost] [ActionName (  thumbnail   " )]  public  void  addthumbnailimage ( ID);}  

We can send a GET request with a URI of "api/products/thumbnail/id" to the map to Getthumbnailimage method.

Send a POST request with the URI "api/products/thumbnail/id" to the map to Addthumbnailimage method.

As you can see from the previous examples, you can use the IDENTITY property to configure an action method to use as the name and method of a matching route.

-- use the [Nonaction] identity property to specify that a method is not an action method .

Web api-Routing (i)

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.