2
votes

I've created a custom WCF service in SharePoint 2010 which I am trying to call via a JQuery Ajax request. My custom WCF service is modeled on the example given here:

Link: http://blog.sharepointbits.com/2010/04/custom-wcf-services-in-sharepoint-2010_17.html

The above method gave me a WCF service I could access from C# server-side code, and a custom InfoPath form, however, I was unable to get a response using JQuery Ajax.

I read elsewhere on Stack Overflow to use MultipleBaseAddressWebServiceHostFactory instead of a MultipleBaseAddressBasicHttpBindingServiceHostFactory as the original article suggest.

Link: Sharepoint 2010 wcf service. call method with jquery

This worked, allowing me to contact (but not authenticate to) the service via JQuery Ajax, however,

a) I am no longer able to navigate to http://[servername]/_vti_bin/Service.svc/mex and see a WSDL. This problem means my InfoPath forms cannot connect to the service either, because they look for a WSDL.

b) Even though the JQuery Ajax request hits the custom WCF service, the browser asks me for authentication every single time, even though the request comes from the browser of a user logged into SharePoint.

If anyone knows how to fix issues a) and b) I'd be very appreciative. It really shouldn't be so difficult to make a service that can be used from any application.

1
If you find the solution, please provide it as an answer here. I'm interested.Kyberias

1 Answers

1
votes

After some mucking around, I stuck with the using MultipleBaseAddressBasicHttpBindingServiceHostFactory. Instead of trying to contact the WCF Service via JSON, I made a function to create a SOAP message, send that to the WCF service, and then parse the result.

Interestingly, this seems to have solved my authentication issue as well, although I'm not clear as to why.

Now the service is usable from InfoPath and from JavaScript.

For reference, a SOAP message to WCF from JavaScript should look like:

<soap:Envelope xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:soap="http://schemas.xmlsoap.org/wsdl/soap/">                
    <soap:Body>
       <MethodName xmlns="http://tempuri.org/"> 
           <ParamName1>Value</ParamName1>
           <ParamName2>Value</ParamName2>
       </MethodName> 
    </soap:Body> 
 </soap:Envelope>

And the JQuery to send it:

$.ajax({
    type: "POST",
    url: url,
    data: soapEnvelope,
    timeout: timeOut,
    contentType: "text/xml",
    dataType: "xml",
    beforeSend: function (xhr) {
        xhr.setRequestHeader("SOAPAction", 'http://tempuri.org/' + methodPath);
    },
    success: onSuccess,
    error: onFailure
});

Note: The easiest way to find out what the value of methodPath should be is to look at the WSDL for your service.