我有一个简单的web api控制器操作方法:
public class WeightController : ApiController
{
[HttpGet]
[AcceptVerbs("GET")]
public int GetWeight(int weightId)
{
return 5;
}
}
我使用webapi的默认路由配置
public static void Register(HttpConfiguration config)
{
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{id}",
defaults: new { id = RouteParameter.Optional }
);
}
我需要进行跨域调用,所以我使用jsonp调用:
$.ajax({
url: 'api/Weight/1',
type: 'GET',
dataType: 'jsonp',
crossDomain: true,
success: function(data) {
alert('success:' + data);
},
error: function(jqXHR,status,error) {
alert('error');
}
});
我收到以下回复(代码404):
"No HTTP resource was found that matches the request URI
'http://localhost:31836/api/Weight/1?callback=jQuery18204532131106388192_1372242854823&_=1372242854950'.",
"MessageDetail":"No action was found on the controller 'Weight' that matches the request."
映射此jsnop请求的正确操作方法定义应该是什么? 如您所见,jsonp添加了回调参数。它是否也应该在动作参数中映射?它在那里是无关紧要的!
任何帮助赞赏=]
答案 0 :(得分:2)
控制器方法中参数的名称需要与route参数匹配。将您的方法更改为:
public int GetWeight(int id)
{
return 5;
}
答案 1 :(得分:0)
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{id}",
defaults: new {
id = RouteParameter.Optional,
action = "GetWeight"
}
);
或将GetWeight
操作重命名为Index