I've been trying to resolve my issue with this answer but I'm having no luck.
Overall, I've created a WCF project with a number of functions in which I would like to access via AJAX (via javascript in my html page).
Here's an example of a function within my web service:
iService
[OperationContract]
[WebInvoke(ResponseFormat = WebMessageFormat.Json)]
string GetStuff();
Service
public string GetStuff()
{
string url = string.Format("http://myapi.co.uk/api/mystuff");
WebRequest myReq = WebRequest.Create(url);
// Where USERNAME and PASSWORD are constants
string usernamePassword = USERNAME + ":" + PASSWORD;
CredentialCache mycache = new CredentialCache();
mycache.Add(new Uri(url), "Basic", new NetworkCredential(USERNAME, PASSWORD));
myReq.Credentials = mycache;
myReq.Headers.Add("Authorization", "Basic " + Convert.ToBase64String(new ASCIIEncoding().GetBytes(usernamePassword)));
WebResponse wr = myReq.GetResponse();
Stream receiveStream = wr.GetResponseStream();
StreamReader reader = new StreamReader(receiveStream, Encoding.UTF8);
string content = reader.ReadToEnd();
return content;
}
Please note that I have also tried returning the Stream
directly also.
Over to my javascript and ajax!
function getData()
{
jQuery.support.cors = true;
$.ajax({
type: "GET",
url: "http://localhost:15574/Service1.svc/GetStuff",
contentType: "application/json; charset=utf-8",
dataType: "jsonp",
success: function(result) {
alert(result);
},
error: function(msg) {
alert("Fail: " + msg.status + ":" + msg.statusText);
}
});
}
I hit the error section, but strangely with a success error message...
I originally thought the issue was because the JSON from the external API was incorrectly formatted, but I tried changing my web service to return some perfectly valid JSON and the same error was displayed. Like I mentioned also, I tried changing my webservice to return the Stream but I had no luck.
Any help with this would be appreciated and I would be very grateful.
Updates
P.S. It appears to work fine in WCF Test Client, returning a string with what I expect.
P.P.S Just added another parameter to the error function to get its status, I'm getting parsererror
P.P.P.S The 3rd parameter passed to error is jquery171014696656613195724_1341477967656 was not called