设为首页收藏本站Access中国

Office中国论坛/Access中国论坛

 找回密码
 注册

QQ登录

只需一步,快速开始

返回列表 发新帖
查看: 1378|回复: 0
打印 上一主题 下一主题

ASP.NET WebApi 路由匹配及参数传递(二)

[复制链接]

点击这里给我发消息

跳转到指定楼层
1#
发表于 2021-9-16 12:10:41 | 只看该作者 回帖奖励 |倒序浏览 |阅读模式
本帖最后由 zhuyiwen 于 2021-9-16 12:12 编辑

三、初步测试

运行项目,在浏览器中访问 http://localhost:65134/api/value,可得到如下结果:(注:使用Chrome浏览器/360极速浏览器)
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 中有很多约定俗成规定。

来自群组: ACC应用开发心得交流
分享到:  QQ好友和群QQ好友和群 QQ空间QQ空间 腾讯微博腾讯微博 腾讯朋友腾讯朋友
收藏收藏 分享分享 分享淘帖 订阅订阅
您需要登录后才可以回帖 登录 | 注册

本版积分规则

QQ|站长邮箱|小黑屋|手机版|Office中国/Access中国 ( 粤ICP备10043721号-1 )  

GMT+8, 2024-4-24 15:01 , Processed in 0.093900 second(s), 24 queries .

Powered by Discuz! X3.3

© 2001-2017 Comsenz Inc.

快速回复 返回顶部 返回列表