This XML file does not appear to have any style information associated with it. The document tree is shown below.
<ArrayOfstring xmlns:i="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://schemas.microsoft.com/2003/10/Serialization/Arrays">
<string>value1</string>
<string>value2</string>
</ArrayOfstring>
而访问 http://localhost:65134/api/value/5 得到的结果如下:
This XML file does not appear to have any style information associated with it. The document tree is shown below.
<string xmlns="http://schemas.microsoft.com/2003/10/Serialization/">value</string>
呵呵,可以看出,http://localhost:65134/api/value 路由到了 public IEnumerable<string> Get() 方法,而 http://localhost:65134/api/value/5 路由到了 public string Get(int id)。
测试表明,Web Api 的访问方法为:方法 + 路径,根据方法使用路由模板进行匹配,本例中的路由模板为 routeTemplate: "api/{controller}/{id}"。
由于是在浏览器中的地址栏填入访问地址,故方法为“GET”方法,访问地址根据路由模板进行访问 Web Api,例如访问 http://localhost:65134/api/value/5
http://localhost:65134 为网站地址
api 为模板中固定的 api
value 为模板中的 controller
5 为模板中的 id,是可选项
注:使用浏览器测试 Web Api 并不是一个好主意,它不太好测试其它诸如 POST/PUT/DELETE 方法。建议使用大名顶顶的 Fiddler 神器,可以构造参数和选择方法。呵呵,个人认为最好的测试办法是
编写一个网页,在网页中使用 jQuery Ajax 编写一段小程序在 Chrome浏览器/360极速浏览器中进行测试,因为 Chrome 的调试工具箱非常强大。
四、路由机制
例如访问 http://localhost:65134/api/value/5,首先 Web Api 匹配路径中的 "api" 确定是 Web Api 访问,再匹配 “value” 找到控制器 “ValueController”,再根据访问方法“GET”,在控制器类中匹配定义为“HttpGet”的方法,在本例中有两个,public IEnumerable<string> Get() 和 public string Get(int id),最终根据“5”来匹配有参数的 public string Get(int id)方法。它不是根据控制器方法名称来匹配的(是不是很郁闷?)
注:约定俗成,控制器中方法名称以“Get”开头的方法默认为“HttpGet”方法,以此类推,“Post”开头的方法默认为“HttpPost”方法...,它们不必注明[HttpGet]/[HttpPost]...。否则,必须方法定义的上一行用[HttpGet]/[HttpPost]...注明方法。呵呵,ASP.NET Web Api 和 Mvc 中有很多约定俗成规定。