I have a Web API which I am calling using the JQuery ajax function. When I test the service directly (using the Chrome RESTEasy extension) it works fine, however when I call it using the JQuery ajax function I get an error. I'm calling it on port 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);
}
});
...but when I trace it using FireBug Lite the response comes from port 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."}
I think the error is, effectively, due to cross-site scripting being blocked, but I'm not actually cross-site scripting, if you see what I mean.
Has anyone else come across this and been able to fix it?
Edit: Routing config (global.asax.vb) is:
RouteTable.Routes.MapHttpRoute(name:="DefaultApi", routeTemplate:="api/{controller}/{id}", defaults:=New With {Key .id = System.Web.Http.RouteParameter.Optional})
Controller:
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
When I debug it, it doesn't get as far as running the controller, although when calling it through RESTEasy it routes correctly and the controller executes successfully. The only difference seemes to be that wen called through RESTEasy it is (correctly) using
http://127.0.0.1:81
but for some reason when called via JQuery/ajax it seems to be using
http://127.0.0.1:82.
For what it's worth, I've tried using the GET verb set up the same way and it works fine and returns the expected results, so it seems like this is something to do with using the POST verb.
OK, I've just noticed something else. This is a Visual Studio 2012 Cloud project, using the Azure emulators for local development. When I run the solution, the following two lines appear in the log:
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.
So it looks like the reason the api can't be found is that the api is being moved to another port but the main application (it is all on one project in the solution) is remaining on the same port and the code assumes that the api is on the same port as the application.
I'm not sure how to fix it, but it looks like this may be the root cause.