Office中国论坛/Access中国论坛
标题:
ASP.NET WebApi 路由匹配及参数传递(三)
[打印本页]
作者:
zhuyiwen
时间:
2021-9-17 11:54
标题:
ASP.NET WebApi 路由匹配及参数传递(三)
本帖最后由 zhuyiwen 于 2021-9-17 12:06 编辑
五、变个花样
在 ValueController 控制器中添加一个新方法,
// GET api/value?key={key}&value={value}
[HttpGe]
public string KeyValue(string key, string value)
{
return string.Format("key: {0}, value: {1}", key, value);
}
复制代码
从代码中,可以看出方法名称为
KeyValue
,并不是 Web Api 的方法名称开头(GET/POST/PUT/DELETE),所以,在方法定义的前一行用 [
HttpGet
] 注明,指明它是一个
GET
方法。
再添加一个测试网页,
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
<title>测试Api</title>
<script src="Mobile/lib/jquery-3.4.1/jquery-3.4.1.min.js"></script>
</head>
<body>
<div>
<input id="Button1" type="button" value="测试 /Api/Value" />
</div>
<script type="text/javascript">
function test1() {
$.ajax({
url: '/Api/Value',
method: 'GET',
data: { "key": 'name', "value": 'master' },
success: function (r) {
console.info(r);
}
});
}
</script>
</body>
</html>
复制代码
使用 jQuery Ajax 来测试刚增加的方法。运行工程,在 Chrome/360极速浏览器中打开这个网页,按 F12 键,打开 Chrome Devtool,点击网页中的“测试 /Api/Value”按钮,看到什么
[attach]64152[/attach][attach]64152[/attach]
自然是通过
Ajax
使用
GET
方法调用 Web Api 方法
Api/Value
,并路由到
ValueController
的
KeyValue
方法。
分析:
假设都是使用 Web Api 的 GET 方法。
url: '
/Api/Value/5
'
匹配到
public string
Get(
int
id)
url: '
/Api/Value
', data: {}
匹配到
public
IEnumerable
<
string
> Get()
url: '
/Api/Value
',
data: { "
key
": '
name
', "
value
": '
master
' }
匹配到
public string
KeyValue(
string
key,
string
value)
发挥想像力,你想到了什么?
结论
:Web Api 的调用与控制器中的方法名称
无关
,但与 Web Api 的
方法
(GET/POST/PUT/DELETE)
有关
,与
id
有关
,与
参数
有关
(C# 的重载)。
[groupid=322]ACC应用开发心得交流[/groupid]
欢迎光临 Office中国论坛/Access中国论坛 (http://www.office-cn.net/)
Powered by Discuz! X3.3