3

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...

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

Community
  • 1
  • 1
Lloyd Powell
  • 18,270
  • 17
  • 87
  • 123

2 Answers2

1

Just a quick guess: You're using WebInvokeAttribute but trying to call a service operation using HTTP GET. Default value for Method property of the WebInvokeAttribute is POST (MSDN). Try switching to WebGetAttribute:

[OperationContract]
[WebGet(ResponseFormat = WebMessageFormat.Json)]
string GetStuff();

Alternatively you can set the Method property of the WebInvokeAttribute to GET.

UPDATE

As @Cheeso mentioned, the "Parse error" that you get is due to the fact that the JavaScript engine cannot interpret the data that you're returning because it's just a plain JSON which itself is not a valid expression (imagine that you put it inside the <script></script> tags. This obviously won't work and this is exactly what the browser tries to do).

You need to respect the callback parameter and wrap you response so it becomes a parameters of the function whose name is passed via callback parameter:

// If the ASP.NET compatibility was enabled, you could safely use HttpContext.Current
// It's here just to demonstrate the idea
return string.Format("{0}({1});", HttpContext.Current.Request.QueryString["callback"], content);

Alternatively just set the "dataType" to "json" when making AJAX call.

volpav
  • 5,090
  • 19
  • 27
  • I've just quickly tried both those methods, no luck unfortunately. It works as expected in WCF Test Client. – Lloyd Powell Jul 04 '12 at 15:01
  • I had it as json originally, but I was getting an error (400 Bad Request) and after researching the error the general consensus was that if making a call to an external service then I could not use json on it's own and the only way to get around this was to use jsonp. – Lloyd Powell Jul 05 '12 at 08:00
  • also on another note, HttpContext is null in my WCF service code. – Lloyd Powell Jul 05 '12 at 08:03
  • @ThePower: HttpContext is null because the ASP.NET compatibility is not enabled (I mentioned this in the code). You either need to user OperationContext or enable ASP.NET compatibility ([MSDN](http://msdn.microsoft.com/en-us/library/ms752234.aspx)) – volpav Jul 05 '12 at 12:21
  • @ThePower: WCF "404 Bad Request" is very easy to troubleshoot using WCF Trace Viewer ([MSDN](http://msdn.microsoft.com/en-us/library/ms732023.aspx)). – volpav Jul 05 '12 at 12:24
1

You have dataType : 'jsonp' in your jquery code. This tells jQuery to append a callback=XXXX to the URL.

The server-side of this dialogue needs to wrap the JSON result in that callback. But your code doesn't do that.

Are you sure you want jsonp?

You might be able to fix this by using dataType: 'json'

Cheeso
  • 189,189
  • 101
  • 473
  • 713