[Web API series tutorial] 2.1-Routing Mechanism in ASP. NET Web API

Source: Internet
Author: User

[Web API series tutorial] 2.1-Routing Mechanism in ASP. NET Web API

This article describes how ASP. NET Web APIs send (route) HTTP requests to controllers.

Note: If you are familiar with ASP. net mvc, you will find that Web API routing is very similar to MVC routing. The main difference is that Web APIs use HTTP methods to select actions rather than URI paths. You can also use MVC routing in Web APIs. This article does not require any knowledge of ASP. net mvc.

Route table

In ASP. NET Web APIs, a controller is a class used to process HTTP requests. The 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 corresponding action.

To determine which action should be executed, the framework uses the route table described in this section. The Web API Project template of Visual Studio creates a default route table:

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

This route is defined in the WepApiConfig. cs file under the App_Start directory.


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

When the Web API framework receives an HTTP request, it tries its best to match the URI to one of the routing templates in the route table. If no route is matched, the client will receive the 404 error. For example, the following URI matches the default route:

/Api/contacts/1/api/products/gizmo1

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

/contacts/1

Note: The reason why "api" is used in routing is to avoid routing conflicts with ASP. net mvc. That is to say, you can use "/contacts" to match the MVC route and use "api/contacts" to match the Web API route. If you do not like this Convention, you can modify the default route table.

Once a route matches, the Web API selects the corresponding controller and action:

To locate the Controller, Web API adds "controller" to the {Controller} variable. To find the action, the Web API traverses the HTTP method and finds an action whose name starts with the name of the HTTP method. For example, if there is a GET request, the Web API will search ...." For example, "GetContact" or "GetAllContacts ". This method is only applicable to GET, POST, PUT, and DELETE methods. You can enable other HTTP methods by using attributes in your controller. You will see an example later (hyperlink to Section 3 of this chapter ...... Other placeholder variables of the routing template, such as {id}, are mapped to the parameters of the action.

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

public class ProductsController : ApiController
{
    public void GetAllProducts() { }
    public IEnumerableGetProductById(int id) { }
    public HttpResponseMessage DeleteProduct(int id){ }
}

Here are some possible HTTP requests and corresponding actions:

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 URI is mapped to the id parameter of the action if it exists. In this example, the controller defines two GET methods, one containing the id parameter, and the other without the id parameter.

Similarly, it is noted that the POST request will fail because "POST…" is not defined in the controller ..." Method.

Routing Variations)

The previous section describes the basic routing mechanism of ASP. NET Web APIs. This section describes some changes.

HTTP Method

In addition to naming conventions for these HTTP methods, you can also assign these actions to specific HTTP methods by using the HttpGet, HttpPut, HttpPost, or HttpDelete attributes.

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

public class ProductsController : ApiController
{
    [HttpGet]
    public Product FindProduct(id) {}
}

To allow an action to support multiple HTTP methods or HTTP methods except GET, PUT, POST, and DELETE, you can use the AcceptVerbs attribute, which takes an HTTP Method list as a parameter.

public class ProductsController : ApiController
{
    [AcceptVerbs("GET", "HEAD")]
    public Product FindProduct(id) { }

    // WebDAV method
    [AcceptVerbs("MKCOL")]
    public void MakeCollection() { }
}
Route by action name

With the default routing template, Web APIs use the HTTP method to select actions. However, you can also create a route table that includes the 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 is named an action Method in the controller. In this type of routing, you should use attributes to specify the allowed HTTP methods. For example, assume that your controller has the following methods:

public class ProductsController : ApiController
{
    [HttpGet]
    public string Details(int id);
}

In this case, GET requests for "api/products/details/1" are mapped to the Details method. This style of routing is very similar to ASP. net mvc and may be suitable for RPC-style APIs.

You can use the ActionName attribute to override the action name. In the following example, two actions are mapped to "api/products/thumbnail/id. One supports GET and 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 executed as an action, you can use the NonAction attribute. This framework indicates that this method is not an action, even if it may match the routing rule.

// Not an action method.
[NonAction]  
public string GetPrivateData() { ... }


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.