AJAX调用可以';找不到我的WebAPI控制器
我有以下AJAX调用:AJAX调用可以';找不到我的WebAPI控制器,ajax,asp.net-web-api,asp.net-mvc-routing,Ajax,Asp.net Web Api,Asp.net Mvc Routing,我有以下AJAX调用: var params = { provider: "facebook" }; $.ajax({ url: "http://localhost/taskpro/api/account/ExternalLogin", data: JSON.stringify(params), type: "POST", contentType: 'application/json; charset=utf-8' }) .done(function (
var params = {
provider: "facebook"
};
$.ajax({
url: "http://localhost/taskpro/api/account/ExternalLogin",
data: JSON.stringify(params),
type: "POST",
contentType: 'application/json; charset=utf-8'
})
.done(function (response) {
alert("Success");
});
调用以下WebAPI控制器:
public class AccountController : ApiController
{
[HttpPost]
[AllowAnonymous]
public bool ExternalLogin(string provider)
{
return true;
}
}
使用以下路线图:
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{action}/{id}",
defaults: new { id = RouteParameter.Optional }
);
当我执行此操作时,fiddler返回:
{"Message":"No HTTP resource was found that matches the request URI
'http://localhost/taskpro/api/account/ExternalLogin'.","MessageDetail":
"No action was found on the controller 'Account' that matches the request."}
我还打了几个其他的电话给这个控制器,效果很好。就是这个电话给我带来了麻烦
另外,如果我删除控制器中的参数,那么
public bool ExternalLogin()
在ajax中注释掉数据行,效果很好
你知道为什么这个电话的路由不起作用吗?我读过这篇文章: 基本上,WebAPI不能绑定到字符串之类的基本数据类型。您必须创建要绑定到的模型,或者使用[FromBody]属性。我将我的方法修改为:
public bool ExternalLogin([FromBody]string provider)
现在它工作得很好。仅供参考..默认情况下,
string
数据类型从Uri绑定,因此在本例中,Web API试图在Uri中找到名为provider
的键的值(路由数据和查询字符串参数)!