码迷,mamicode.com
首页 > Windows程序 > 详细

WebApi初探之路由配置

时间:2015-08-05 10:09:02      阅读:246      评论:0      收藏:0      [点我收藏+]

标签:

本文介绍了ASP.NET Web API路由HTTP请求控制器。

如果你熟悉ASP.NET MVC,Web API路由是和MVC路由非常相似的。主要差别是Web API使用HTTP方法而不是URI路径来选择Action的。你也可以使用MVC的路由配置风格来配置Web API路由,当然本文不是来介绍ASP.NET MVC的。

路由表

在ASP.NET Web API,控制器是一种处理HTTP请求的类。控制器的公共方法被称为动作方法或简单的动作。当Web API框架接收请求时,它将请求发送到一个动作。

要确定调用哪个动作,该框架使用路由表。Visual Studio项目模板为Web API创建了一个默认的路由:                 

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

这个路由在位于App_Start文件夹中的WebApiConfig.cs文件中定义:

技术分享

如果想要知道更多相关的配置,你可以访问Configuring ASP.NET Web API .

如果是自主机Web API,你必须设置路由表直接在HttpSelfHostConfiguration对象.想知道更多相关信息,请访问Self-Host a Web API.

路由表中的每一个条目包含一个路由模板。Web API默认的路由模板是"api/{controller}/{id}". 在这个模板中, "api"是固定路径量, {controller} 和 {id} 都是预置位变量.

当Web API框架接收到一个HTTP请求,它将尝试匹配URI对路由表中的路由模板。如果没有匹配到,客户端将收到一个404错误。例如,可以用下列地址来匹配默认的路由规则:

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

但是,下面这个路径将匹配不到,因为它缺少了"api"这个固定路径量:

  • /contacts/1

Note: The reason for using "api" in the route is to avoid                 collisions with ASP.NET MVC routing. That way,                 you can have "/contacts" go to an MVC controller, and "/api/contacts" go to a Web                 API controller. Of course, if you don‘t like this convention, you can change the                 default route table.

Once a matching route is found, Web API selects the controller and the action:

  • To find the controller, Web API adds "Controller" to the value of the                 {controller} variable.
  • To find the action, Web API looks at the HTTP method, and then looks for                 an action whose name begins with that HTTP method name. For example, with a GET request, Web API looks for an action that starts with "Get...",                 such as "GetContact" or "GetAllContacts".  This convention applies only to                 GET, POST, PUT, and DELETE methods. You can enable other HTTP methods by using attributes                 on your controller. We’ll see an example of that later.
  • Other placeholder variables in the route template, such as {id}, are                     mapped to action parameters.

Let‘s look at an example. Suppose that you define the following controller:

public class ProductsController : ApiController
{
    public void GetAllProducts() { }
    public IEnumerable<Product> GetProductById(int id) { }
    public HttpResponseMessage DeleteProduct(int id){ }
}

Here are some possible HTTP requests, along with the action that gets invoked for each:

HTTP MethodURI PathActionParameter
GET api/products GetAllProducts (none)
GET api/products/4 GetProductById 4
DELETE api/products/4 DeleteProduct 4
POST api/products (no match)  

Notice that the {id} segment of the URI, if present, is mapped to the         id parameter of the action. In this example, the controller defines two         GET methods, one with an id parameter and one with no parameters.

Also, note that the POST request will fail, because the controller does not                 define a "Post..." method. 

Routing Variations

The previous section described the basic routing mechanism for ASP.NET Web API. This section describes some variations.

HTTP Methods

Instead of using the naming convention for HTTP methods, you can explicitly specify the HTTP method for an action by decorating the action                 method with the HttpGet, HttpPut,                 HttpPost, or HttpDelete attribute.

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

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

To allow multiple HTTP methods for an action, or to allow HTTP methods other than GET, PUT, POST, and DELETE, use     the AcceptVerbs attribute, which takes a list of HTTP methods.

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

    // WebDAV method
    [AcceptVerbs("MKCOL")]
    public void MakeCollection() { }
}

Routing by Action Name

With the default routing template, Web API uses the HTTP method to select the action.     However, you can also create a route where the action name is included in the URI:

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

In this route template, the {action} parameter names the action method     on the controller. With this style of routing, use attributes to specify the                 allowed HTTP methods. For example, suppose your controller has the following method:

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

In this case, a GET request for “api/products/details/1” would map to the Details                 method. This style of routing is similar to ASP.NET MVC, and may be appropriate                 for an RPC-style API.

You can override the action name by using the ActionName attribute.                 In the following example, there are two actions that map 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 getting invoked as an action, use the NonAction                 attribute. This signals to the framework that the method is not an action, even                 if it would otherwise match the routing rules.

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

Further Reading

This topic provided a high-level view of routing. For more detail, see Routing and Action Selection, which describes exactly how the framework matches a URI to a route, selects a controller, and then selects the action to invoke.

 

原文地址:http://www.asp.net/web-api/overview/web-api-routing-and-actions/routing-in-aspnet-web-api

WebApi初探之路由配置

标签:

原文地址:http://www.cnblogs.com/ziranquliu/p/4703840.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!