Reputation: 1023
So I have a simple WebAPI Controller with...
[HttpGet]
public string Demo()
{
System.Diagnostics.Debug.Print("API Demo call hit " + DateTime.Now.ToString());
return "Got Here";
}
Because of the Debug output, I can tell that it is actually getting called from my javascript. So I know that my script is at least connecting. I also know that if I put a break on the line.. the script (html page) does pause and wait until I let the code continue. So they are talking, but I have 2 issues...
1) Every time I make a send call, I get the script error "NetworkError: Failed to execute 'send' on 'XMLHttpRequest': Failed to load 'http://localhost:64769/api/demo'" ... even though I know it is talking to it. But I did notice that if I do NOT trap for errors, the script fails on the "Send" line and doesn't continue.
2) However, with the error trap, the script does continue (as expected) but the XMLHttpRequest doesn't have my return. (e.g. responseText is blank).. pretty much every single property of the object is blank or null.
So I think my response is empty because there is a problem with the "send". However because it is actually calling my Controller and waiting on it to run, I'm lost as to what the problem is?
Here is my script...
function CallWebAPI()
{
var displayResults = document.getElementById('responseDetails');
var xmlhttp = new XMLHttpRequest();
xmlhttp.open("GET", "http://localhost:64769/api/demo", false);
try
{
xmlhttp.send();
}
catch(err)
{
displayResults.innerHTML += err + "<br />";
}
displayResults.innerHTML += "The Results...<br />";
for (var key in xmlhttp)
{
displayResults.innerHTML += key + "---" + xmlhttp[key] + "<br />";
}
}
Upvotes: 1
Views: 54
Reputation: 1023
All,
So after an entire day and half of messing around, finally figured it out. I guess I was running an HTML file from my desktop, and my Web Service was running on http://localhost:64769.
This is one of those cross domain things. When using an HTTP client in .NET, I did not have to deal with this.. but once I tried to use a client other than .NET, my Web service actually responded.. but the client Browser would not accept the response.
The fix was to change my api service to...
[HttpGet]
public HttpResponseMessage Demo()
{
string myReturnMessage = "API Demo call hit " + DateTime.Now.ToString();
System.Diagnostics.Debug.Print(myReturnMessage);
HttpResponseMessage myReturn = this.Request.CreateResponse(System.Net.HttpStatusCode.OK, myReturnMessage);
//This was the KEY!!!!
myReturn.Headers.Add("Access-Control-Allow-Origin", "*");
return myReturn;
}
Upvotes: 1