web api :Routing in ASP.NET Web API

 

 

Web API 和SignalR都是在服务层。

If you are familiar with ASP.NET MVC, Web API routing is very similar to MVC routing.

The main difference is that Web API uses the HTTP method, not the URI path, to select the action.(web api和mvc路由最主要的区别是,mvc是使用URI路径来选择action的,而web api 则是使用http方法来选择action的。)

You can also use MVC-style routing in Web API. This article does not assume any knowledge of ASP.NET MVC.

 

参考官网:http://www.asp.net/web-api/overview/web-api-routing-and-actions/routing-in-aspnet-web-api

 

1.路由表

 

1.1默认配置

默认的路由映射,所以,调用api的时候,必须以api开头

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

 

eg:

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

 

而 /contacts/1就不会成功。

 

1.2默认约定

默认的约定,以Get,Delete,Put,Post这些开头的方法:

  1. public class ProductsController : ApiController
  2. {
  3.     public void GetAllProducts() { }
  4.     public IEnumerable<Product> GetProductById(int id) { }
  5.     public HttpResponseMessage DeleteProduct(int id){ }
  6. }

 

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)

  

 

2.路由变量

 

2.1 Http方法

 

使用HttpGet, HttpPut, HttpPost, or HttpDelete 来进行标记方法。

也可以使用[AcceptVerbs("GET", "HEAD")]来标记多个选择。

 

2.2使用ActionName来路由

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

则以上的配置可以支持两种:

One is

  1. public class ProductsController : ApiController
  2. {
  3.     [HttpGet]
  4.     public string Details(int id);
  5. }

 

The other is:(api/products/thumbnail/id

  1. public class ProductsController : ApiController
  2. {
  3.     [HttpGet]
  4.     [ActionName("Thumbnail")]
  5.     public HttpResponseMessage GetThumbnailImage(int id);
  6.  
  7.     [HttpPost]
  8.     [ActionName("Thumbnail")]
  9.     public void AddThumbnailImage(int id);
  10. }

 

2.3非Action

 

使用[NonAction] 标记方法。

posted @ 2015-10-22 17:52  _DN  阅读(286)  评论(0编辑  收藏  举报