ASP. NET Web API (c)

Source: Internet
Author: User

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 action. When the Web API receives a request, it routes the request to an action.

Note: The routing of the Web API is very similar to the route of ASP. The main difference is that the Web API uses an HTTP method instead of a URI path to select the action

To determine which action was invoked, the framework uses a registry. The project template for Visual Studio's Web API creates a default route:

1   CONFIG. Routes.maphttproute (2                 "defaultapi",                 3  "Api/{controller}/{id}",4                 new {id =  Routeparameter.optional}5 );

This route is defined in the Webapiconfig file, which is located in the App_start directory

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/product
    • /api/product/1
    • /api/product?category=category

However, the following URI does not match because it lacks the "API" field

    • /product/1

Note: The reason for using "API" in routing is to avoid routing conflicts with ASP. In this way, "/product" can be used to enter a controller, and "/api/product" into 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 will add "controller" 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 a "get." Starting with the action, this Convention applies only to the Get,post,put,delete method, and by using attribute on the controller, you can start other HTTP methods

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

Routing Variations Routing Change HTTP method

Instead of naming conventions that use HTTP methods, you can explicitly specify an HTTP method for an action by using the Httpget,httppost,httpput or Httpdelete property to fit the action method

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

1 [HttpGet] 2  Public Product findproduct (int  ID)3{4    return repository. Get (ID); 5 }

The above code needs to be annotated with the getproduct (int id) written above;

Because if the Web API is not commented, it matches multiple operation errors to the request match

The Web API allows an action to correspond to multiple HTTP methods;

1[Acceptverbs ("GET","POST"," HEAD ")]2  PublicProduct Findproduct (intID)3 {4     returnRepository. Get (ID);5 }6[Acceptverbs ("Mkcol")]7  Public voidmakecollection ()8 {9 Ten}

The first method: Indicates that the action receives HTTP's Get,post and head methods.

The second method: The WebDAV method, a Web-based distributed work and version-controlled HTTP method, is an extended HTTP method that Mkcol a method that is subordinate to WebDAV, which creates a collection at the location specified by the URI.

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 in the URI that contains the action name

1 CONFIG. Routes.maphttproute (2           "defaultapi",3           "  Api/{controller}/{action}/{id}",4           new {id = Routeparameter.optional} 5 );

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

12publicstring Details (int

In this case, a GET request "API/PRODUCT/DETAILS/1" will be mapped to this detail method. This style of routing is similar to ASP. NET MVC, and may be close to the RPC-style API.

You can also override the action name by using the ActionName annotation property. In the following example, there are two action mappings to "API/PRODUCT/THUMBNAIL/ID". One support get, one support post

1 [HttpGet] 2 [ActionName ("Thumbnail")]3 Public Httpresponsemessage getthumbnailimage (int  ID); 4 [HttpPost] 5 [ActionName ("Thumbnail")]6 Public void Addthumbnailimage (int
Nonactions

To prevent a method from being requested as action, you can use the Nonaction annotation property. It sends a signal to the framework: This method is not an action, even if it may match the routing rule

1 [Nonaction] 2  Public void Isnoaction ();

Route Templates

The routing template looks like a URI path, but it can have placeholders and is indicated by {}:

" Api/{controller}/public/{category}/{id} "

When creating a route, you can provide default values for some or all of the placeholders

New "  All " }

You can provide a constraint that restricts how the URI fragment matches the placeholder

New @" \d+ " }   // match only if "id" is one or more digits

The above statement restricts the value of the fragment by a regular expression, which indicates that the ID fragment matches only one or more digits, so the ID fragment in the URI must be a number to match the route.

This framework attempts to match the fragment in the URI path to this template. The text in the template must match exactly. A placeholder can match any value unless you specify a constraint. This framework does not have another part of the URI, such as a host name or a query string. This framework selects the first matching route in the routing table.

This has two special placeholders: "{Controller}" and "{Action}".

{Controller} provides the name of the director

{Action} provides an action name. In the Web API, the usual convention is to ignore {Action}.

Defaults (default value)

If you provide a default value, then this route matches the missing URI for these fragments. For example

1 routes. Maphttproute (2     "defaultapi"3     " Api/{controller}/{category} "  4     new"all" 5);

This URI "Http://localhost/api/products" is matched to this route. The "{category}" fragment will be assigned the default value "all".

Route Dictionary (Route field)

If the framework finds a matching URI, it creates a dictionary containing each placeholder value. This key value is a placeholder name without {}. This value is taken from the URI path or the default value. This field is present in the Ihttproutedata object. This special {Controller} and {Action} placeholders are handled the same as other placeholders during the match routing phase, and they are stored in a dictionary with a different value.

You can use a special routeparameter.optional value in the default value. If a placeholder is given this value, the value will not be added to the dictionary, for example

12     "defaultapi"3      "  Api/{controller}/{category}/{id}"4     new "  all", id =5 );

For the URI path "Api/product", the routing dictionary will contain: controller: "Product", Category: "All"

However, for "api/product/toys/123", the routing dictionary will contain: controller: "Product", Category: "Toys"

This default value can also contain values from a route template that does not appear. If this route matches, the value is stored in the routing dictionary. For example

12     "Root"3     "api/ Root/{id}"4     new"product" , id =5 );

If the URI path is "Api/root/7", the dictionary will contain two values: Controller: "Product", ID: "8".

Selecting a Controller

Controller selection is handled by the Ihttpcontrollerselector.selectcontroller method. This method takes the httprequestmessage instance as a parameter. and return to Httpcontrollerdescriptor.

Its default implementation is provided by the Defaulthttpcontrollerselector class. This class uses a straightforward algorithm:

1. Find the "controller" key for the routing dictionary.

2. Obtain the value of this key and attach the string "controller" to get the type name of the controller.

3. Find the Web API controller with this type name

For example, if the key-value pair for a routing dictionary is "controller" = "Product", then the controller type is "Productcontroller". If there is no match, or multiple matches, the WEB API framework returns an error to the client.

For step 3,Defaulthttpcontrollerselector uses the ihttpcontrollertyperesolver interface to obtain a list of Web API control types. The default implementation of Ihttpcontrollertyperesolver returns all public classes that meet the following criteria:

    1. Classes that implement Ihttpcontroller
    2. Non-abstract class
    3. Classes with names ending with "Contoller"

Action Selection

When the controller is selected, the WEB API framework selects the action by calling the Ihttpactionselector.selectaction method. This method takes Httpcontrollercontext as the parameter and returns the Httpactiondescriptor.

This default implementation is provided by the Apicontrolleractionselector class. In order to select an action, the following areas are found:

    1. Methods for HTTP Requests
    2. The action placeholder for this routing template
    3. Parameters of the action in the controller

Before we look at the selection algorithm, we need to understand some things about the controller action

What methods of the controller are considered as action? When you select an action, the framework only examines the public instance method of the controller. Moreover, it excludes special name methods (constructors, events, operators, overloads, etc.), and class methods that integrate self-apicontroller

HTTP Methods

The WEB API framework selects only the action that matches the requested HTTP method, determined as follows

    1. You can specify the HTTP method with the annotation attribute acceptverbs,httpdelete,httpget,httppost,httpoptions,httppatch,httppost or httpput.
    2. If the Controller method name starts with get,post,put,delete,head,options or patch, the action will support the appropriate HTTP method according to this Convention.
    3. If none of the above is true, then this method will only support post requests.

Parameter Bindings

Parameter binding refers to how the Web API creates parameter values. The following are the default rules for parameter bindings:

1. Simple type taken from URI

2. Complex type taken from request body

The simple type includes all. NET Framework Simple Type ", plus, datetime,decimal,guid,string and TimeSpan. For each action, at most one parameter can read the request body.

In this context, the action selection algorithm is as follows

    1. Create a list of all actions in the controller that match the HTTP request method
    2. If the routing dictionary has an action entry, remove the action that does not match the entry value
    3. An attempt was made to match the action argument to the URI, as follows

A: For each action, get a simple type of argument list, which is where the URI parameter is bound to get. The list does not include optional parameters

B: From this list, try to find the matching of each parameter in the routing dictionary or in the URI query string. Matches are case-insensitive and are not related to the order of the parameters

C: Select such an action, each parameter in the list has a match in the URI

D: If there are more than one action to satisfy these conditions, select the one with the most parameters.

4. Ignore the action labeled with the [nonaction] annotation attribute.

The 3rd step may rang people. The basic idea is that you can get parameter values from a URI, or a request body, or a custom binding. For parameters from URIs, we want to make sure that the URI actually contains a value for this parameter in its path (through the routing dictionary) or in the query string.

For example, consider the following action

 Public void Get (int ID)

Its ID is bound to the URI. Therefore, this action can only match the URI that contains the ID value in the Routing dictionary or query string

Optional parameters are an exception because they are optional. For optional parameters, it is not related if the binding cannot get its value through a URI.

A complex type is an exception to another cause. A complex type can only be bound to a URI by a custom binding. However, in this case, the WEB API framework cannot know in advance whether this parameter is bound to a special URI. To find out, this framework needs to invoke this binding. The purpose of the selection algorithm is to select an action based on a static description before invoking the binding. Therefore, the responsible type is outside the matching algorithm.

After the action is selected, all parameter bindings are called.

Summary:

    1. The action must match the requested HTTP method.
    2. The action name must match the action entry in the routing dictionary, if any.
    3. For each parameter of the action, if the argument is from a URI, the parameter name must be found in the routing dictionary or URI query string (except for optional and complex parameter types)
    4. An attempt was made to match the maximum number of arguments. The best match may be a parameterless method.

Extended Points

The Web API provides extensibility points for some parts of the routing process.

To provide your own implementation for any of these interfaces, you can use the Services collection of the Httpconfiguration object:

var config = globalconfiguration.configuration;config. Services.replace (typeofnew mycontrollerselector (config));

ASP. NET Web API (c)

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.