我有一个简单的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添加了回调参数。它是否也应该映射到动作参数中?那里是不可救药的!
感谢任何帮助=]
控制器方法中的参数名称需要与路由参数匹配。将您的方法更改为:
public int GetWeight(int id)
{
return 5;
}
问题似乎正在解决中。尝试修改:
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{id}",
defaults: new {
id = RouteParameter.Optional,
action = "GetWeight"
}
);
或将GetWeight
操作重命名为Index