Routing of the "reprint" ASP. NET MVC Web API

Source: Internet
Author: User

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

routing table

In the ASP. NET Web API, a controller is a class used to handle HTTP requests. The public method used to process HTTP requests in this class is called action method or short action. When a request is received by the Web API framework, the request is routed to an action to be processed.

The ASP. NET WEB API framework uses a routing table to determine which action method is called. The ASP. NET Web API project template in Visual Studio creates a default route:

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

This default route is defined in the WebApiConfig.cs file in the App_start directory.

For more information about the Webapiconfig class, see the Configuring ASP. NET Web API.

Each record in the routing table contains a route template. The Default Web API routing template is "Api/{controller}/{id}". In this template, "API" is a fixed value, while {controller} and {ID} are just placeholders (similar to string.) The formatted string in the Format method uses the {0} placeholder).

When the Web API framework receives an HTTP request, it attempts to use the routing template in the routing table to match the requested URI. If there is no matching template, the client receives a 404 error. The following URIs are matched to the default template:

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

But the following URI is mismatched because it lacks the "API" section

/contacts/1

Note: The fixed amount of "API" is used in routing templates to avoid conflicts with ASP. in ASP. NET MVC, you can use "/contacts" to match a normal controller, and use "/api/contacts" to match the controller of the Web API. Of course, if you don't like the convention, you can change the default routing table.

Once a matching routing template is found, the Web API chooses the appropriate controller and action:

1. Select the Controller,web API to find a controller with the same name by adding "controller" after the value matching the {controller} placeholder

2. Select the Action,web API to look for methods that begin with the method of the HTTP request. For example, with a GET request, the Web API looks for a method in the controller that starts with get, such as "getcontact" or "getallcontacts". This Convention applies only to Get,post,put and delete methods, You can enable an HTTP method by adding an attribute to the method, and we'll show you the example later.

3. Other placeholders in the routing template, such as {ID}, are mapped to the action's argument list.

Let's take a look at an example, assuming that a controller is defined as follows

 Public class productscontroller:apicontroller{    publicvoid  getallproducts () {}      Public Ienumerable<product> Getproductbyid (int  ID) {}    public Httpresponsemessage deleteproduct (int  ID) {}}

Here are some possible HTTP requests and the action that is called to

uri Path action parameter
api/products getallpriducts none
get api/produc TS/4 getpriductbyid 4
API/PRODUCTS/4 Deleteproduct 4
post api/products no match  

Note The {ID} section of the URI, if present, the value of this part will be mapped to the parameter named ID of the action method. In this example, the controller defines two get-start methods, one with one parameter named ID and the other without parameters.

Route variations (do not know how to translate, route variant?) )

In addition to using a naming convention, you can display the HTTP method that specifies the action response by adding httpget,httpput,httppost or httpdelete specific to the action.

In the following example, the Findproduct method corresponds to a GET request to http:

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

In order for an action to respond to multiple HTTP method types, or to respond to HTTP method other than Get,put,post,delete four, you can specify the Acceptverbs attribute for the action, which can accept an HTTP Method list.

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

The default route template uses the HTTP method to select the action, but you can also use the name of the action to route it.

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

In this template, the {action} placeholder is the name of the action in the controller, and this form of routing template determines which HTTP method the action responds to by attaching an attribute above the action, for example, Assume that the controller has the following methods

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

In this example, an HTTP GET request that requests "API/PRODUCTS/DETAILS/1" is mapped to the details method, which is similar to the routing style of ASP. NET MVC, and is more suitable for the Rpc-style API ( Remote procedure call style API?)

By using the ActionName property, we can specify a specific action name without using the action's method name, and in the following example, two actions will respond to the URI "Api/products/thumbnail/id", But corresponding to the Get method and Post method, respectively:

 Public class productscontroller:apicontroller{    [HttpGet]    [ActionName ("Thumbnail"  )]    public httpresponsemessage getthumbnailimage (int  ID);    [HttpPost]    [ActionName ("Thumbnail")]      Public void Addthumbnailimage (int  ID);}
Non-action method

For the method in the controller, we do not want to respond to HTTP method, that is, the controller can contain non-action methods, then to add the Nonaction attribute to these methods, so that the web These methods are ignored by the API framework when it makes routing matches.

// Not an action method. [nonaction]    Public string GetPrivateData () {...}

English Original: Http://www.asp.net/web-api/overview/web-api-routing-and-actions/routing-in-aspnet-web-api

Transferred from: http://www.cnblogs.com/onepiece_wang/archive/2013/03/14/2960535.html

Routing of the "reprint" ASP. NET MVC Web API

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.