引
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开头
- routes.MapHttpRoute(
- name: "API Default",
- routeTemplate: "api/{controller}/{id}",
- defaults: new { id = RouteParameter.Optional }
- );
eg:
- /api/contacts
- /api/contacts/1
- /api/products/gizmo1
而 /contacts/1就不会成功。
1.2默认约定
默认的约定,以Get,Delete,Put,Post这些开头的方法:
- public class ProductsController : ApiController
- {
- public void GetAllProducts() { }
- public IEnumerable<Product> GetProductById(int id) { }
- public HttpResponseMessage DeleteProduct(int id){ }
- }
HTTP Method |
URI Path |
Action |
Parameter |
GET |
api/products |
GetAllProducts |
(none) |
GET |
api/products/4 |
GetProductById |
|
DELETE |
api/products/4 |
DeleteProduct |
|
POST |
api/products |
(no match) |
2.路由变量
2.1 Http方法
使用HttpGet, HttpPut, HttpPost, or HttpDelete 来进行标记方法。
也可以使用[AcceptVerbs("GET", "HEAD")]来标记多个选择。
2.2使用ActionName来路由
- routes.MapHttpRoute(
- name: "ActionApi",
- routeTemplate: "api/{controller}/{action}/{id}",
- defaults: new { id = RouteParameter.Optional }
- );
则以上的配置可以支持两种:
One is
- public class ProductsController : ApiController
- {
- [HttpGet]
- public string Details(int id);
- }
The other is:(api/products/thumbnail/id)
- public class ProductsController : ApiController
- {
- [HttpGet]
- [ActionName("Thumbnail")]
- public HttpResponseMessage GetThumbnailImage(int id);
- [HttpPost]
- [ActionName("Thumbnail")]
- public void AddThumbnailImage(int id);
- }
2.3非Action
使用[NonAction] 标记方法。