0

i've built a WCF web application , exposed it's method into get enabled methods

[OperationContract]
[WebGet]
string getStatistics();


[OperationContract]
[WebGet]
string getVenues(string BrandName, int limit);

and edited the config file :

<endpoint address="json" binding="webHttpBinding"  contract="foursquare2RDF.IVenue2rdf" behaviorConfiguration="restBehavior"/>

and in the service behavior :

 <endpointBehaviors>
<behavior name="restBehavior">
          <enableWebScript/>
        </behavior>
      </endpointBehaviors>

i hosted the service on the IIS , and it works very fine from the browser so when u hit :

http://localhost:83/venue2rdf.svc/json/getStatistics

it returns a good results

the problem is i can't consume this restful service from if shows those errors :

OPTIONS http://localhost:83/venue2rdf.svc/json/getStatistics?{'venues':'100'} 405 (Method Not Allowed) 

XMLHttpRequest cannot load [http://localhost:83/venue2rdf.svc/json/getStatistics][1]. Origin null is not allowed by Access-Control-Allow-Origin.

i'm using that code to call the service :

$.ajax({
    type: "get",
    url: statisticsURL,
    data: "{}",
    contentType: "application/json; charset=utf-8",
    dataType: "json",
    success: function (msg) {
        eval("var x = " + msg.d);

        console.log(x);
    }
});

what ive reached so far :

  • i tried replacing $.ajax with $.getjson like stated in similar question and the error 405 was removed , the second error just appears
  • i've found something called Ajax enabled WCF service project , but still i don't want to migrate in to a new project
  • i know there are similar questions but all don't fit , showing different errors that mine
Hady Elsahar
  • 2,001
  • 4
  • 27
  • 46
  • If the project you are calling from is in the same domain as your WCF Service is then the calls from JQuery are possible. If the domain is different then you need to use JSONP as said by @the_ajp and you need to make sure that your WCF handles JSONP requests by writing the result back to the response stream. – Rajesh Jul 27 '12 at 09:59

2 Answers2

1

You should probably make it a JSONP request since your going cross domain, you running into the same origin policy:

$.getJSON(stastatisticsURL + "?callback=?", success: function (msg) {
    eval("var x = " + msg.d);

    console.log(x);
});

the ?callback=? part tels jquery to make it JSONP. I advise you to read up on what JSONP is since it isn't a silver bullet. To enable JSONP on WCF services read:

C# WCF Web API + JSONP

Community
  • 1
  • 1
albertjan
  • 7,411
  • 5
  • 39
  • 70
  • ok , this really works , just i guess the Jquery have problem in parsing the results . it returns un expected token , should i modify the service or something to accept jsonp ? i guess wcf 4.0 natively supports jsonp – Hady Elsahar Jul 27 '12 at 09:57
0

For you to consume a cross domain WCF REST service using jQuery please find a sample below:

My Service looks as below:

    [ServiceContract]
    public interface IJSONPService
    {
        [OperationContract]
        [WebGet]
        string GetDate();

        [OperationContract]
        [WebInvoke]
        string PostData(string name);
    }

Now my config entries for the above service looks as shown:

<services>
    <service name="Service.JSONPService">
        <endpoint address="" binding="webHttpBinding" behaviorConfiguration="json" bindingConfiguration="defaultRestJsonp" contract="Service.IJSONPService">
        </endpoint>
    </service>
</services>
<behaviors>
      <endpointBehaviors>
         <behavior name="json">
             <enableWebScript />
         </behavior>
   </behaviors>
</endpointBehaviors>
<webHttpBinding>
        <binding name="defaultRestJsonp" crossDomainScriptAccessEnabled="true">
          <readerQuotas maxStringContentLength="2147483647" maxArrayLength="2147483647" maxBytesPerRead="2147483647" maxDepth="64" maxNameTableCharCount="2147483647" />
          <security mode="None" />
        </binding>
</webHttpBinding>

You need to note the crossDomainScriptAccessEnabled attribute in the binding element "defaultRestJsonp" which takes care of determining the request to be for JSONP and appropriately converting the response to be wrapped in the callback method from the URL which comes as a query string

Now from your page do the below JavaScript that calls the above WCF REST service as shown:

function TestingWCFRestWithJsonp() {
                $.ajax({
                    url: "http://domain.com/Service/JSONPService.svc/GetDate",
                    dataType: "jsonp",
                    type: "GET",
                    timeout: 10000,
                    jsonpCallback: "MyCallback",
                    success: function (data, textStatus, jqXHR) {
                        alert(data);
                    },
                    error: function (jqXHR, textStatus, errorThrown) {alert('error');

                    },
                    complete: function (jqXHR, textStatus) {alert('complete');
                    }
                });
            }
            function MyCallback(data) {
                alert(data);
            }

Check out the jsonpCallback property in the $.ajax method call.

The raw request to the web service call looks as below:

GET http://localhost/Service/JSONPService.svc/GetDate?callback=MyCallback&_=1343391683779 HTTP/1.1
Host: localhost
Connection: keep-alive

And the raw response from the WCF REST service looks as below:

HTTP/1.1 200 OK
Cache-Control: private
Content-Type: application/x-javascript
Date: Fri, 27 Jul 2012 12:21:23 GMT
Content-Length: 27

MyCallback("27\/07\/2012");

NOTE: When you perform a JSONP request your $.ajax methods error/complete/success are not called.

BenMorel
  • 30,280
  • 40
  • 163
  • 285
Rajesh
  • 7,381
  • 5
  • 19
  • 34