1

我有一个使用 JQuery ajax 函数调用的 Web API。当我直接测试服务(使用 Chrome RESTEasy 扩展)时,它工作正常,但是当我使用 JQuery ajax 函数调用它时,我得到一个错误。我在端口 81 上调用它:

$.ajax({
   url: "http://127.0.0.1:81/api/people",
  data: JSON.stringify(personToCreate),
  type: "POST",
  contentType: "application/json;charset=utf-8",
  statusCode: {
     201: function (newPerson) {
        callback(newPerson);
     }
  },
  success: function (newPerson) {
     alert("New person created with an Id of " + newPerson.Id);
  },
  error: function (jqXHR, textStatus, errorThrown) {
     alert('Error. '+textStatus+'. '+errorThrown);
  }
});

...但是当我使用 FireBug Lite 跟踪它时,响应来自端口 82:

{"Message":"No HTTP resource was found that matches the request URI 'http://127.0.0.1:82/api/people'.","MessageDetail":"No action was found on the controller 'People' that matches the request."}

我认为错误实际上是由于跨站点脚本被阻止,但如果您明白我的意思,我实际上并不是跨站点脚本。

有没有其他人遇到过这个并能够解决它?

编辑:路由配置(global.asax.vb)是:

RouteTable.Routes.MapHttpRoute(name:="DefaultApi", routeTemplate:="api/{controller}/{id}", defaults:=New With {Key .id = System.Web.Http.RouteParameter.Optional})

控制器:

Public Function PostValue(ByVal departmentid As Integer, ByVal emailaddress As String, ByVal firstname As String, ByVal lastname As String) As Guid
    Dim context As New WSMModelDataContext
    Dim bllPeople As New PeopleBLL(context)

    Return bllPeople.Create(firstname, lastname, emailaddress, departmentid)
End Function

当我调试它时,它并没有运行控制器,尽管当通过 RESTEasy 调用它时,它正确路由并且控制器成功执行。唯一的区别似乎是通过 RESTEasy 调用它(正确)使用

http://127.0.0.1:81 

但由于某种原因,当通过 JQuery/ajax 调用时,它似乎正在使用

http://127.0.0.1:82.

对于它的价值,我尝试使用相同的方式设置 GET 动词,它工作正常并返回预期结果,所以这似乎与使用 POST 动词有关。

好的,我刚刚注意到别的东西。这是一个 Visual Studio 2012 Cloud 项目,使用 Azure 模拟器进行本地开发。当我运行解决方案时,日志中出现以下两行:

Windows Azure Tools: Warning: Remapping public port 80 to 81 to avoid conflict during emulation.
Windows Azure Tools: Warning: Remapping private port 80 to 82 in role 'SimplicityWSM' to avoid conflict during emulation.

所以看起来无法找到 api 的原因是 api 被移动到另一个端口,但主应用程序(它都在解决方案中的一个项目上)仍然在同一个端口上,并且代码假设api 与应用程序位于同一端口。

我不确定如何解决它,但看起来这可能是根本原因。

4

0 回答 0