Wednesday, May 8, 2013

Call a Windows Communication Foundation Service with Jquery

I found myself in need to call WCF services from html pages with Jquery,
is not difficult but if you know what to check, you can save a lot of time.

The call 

Is the same as a WebService, WebMethod, with the exception of the extension ".svc"
unnecessary to write yet another Jquery Ajax tutorial:


// Function to call WCF  Service      

        function CallService() {
            $.ajax({
                type:   // GET or POST
                url: // http://..../MyService.svc/GetData
                data: // Data sent to server
                contentType: // content type sent to server (ie: "application/json; charset=utf-8")
                dataType: // Expected data format from server (ie: "json")
                processdata: // True or False
                success: function (msg) {
                   //When service call success
                    ServiceSucceeded(msg);
                },
                error: ServiceFailed // When Service call fails
            });
        }


What about the contract ??


First of all, why "Interface" is called Contract in WCF ? No...is not important,
what is really important, is specify in the contract that you want to operate
with WebInvoke, the type of verb (GET /POST) and the expected data format (Json)


<ServiceContract()>
Public Interface IDataService
    <OperationContract()> _
    <WebInvoke(Method:="POST", ResponseFormat:=WebMessageFormat.Json)>
    Function GetData() As String

     .... yessss VB.Net, why not ?

End Interface

What about the implementation of Interface?

Nothing but remember to specify the AspNet Compatibility before starting to write your Class

Imports System.ServiceModel.Activation

<AspNetCompatibilityRequirements(RequirementsMode:=AspNetCompatibilityRequirementsMode.Allowed)>
Public Class DataService
    Implements IDataService  
   
    Public Function GetData() As String Implements IDataService.GetData

    End Function
End Class


That's all....ops no no, just one last thing:

EndPoint

You have to set your endpoint in the Web.config file:

<endpoint address="" binding="webHttpBinding" bindingConfiguration="WHB" contract="HelloWCF.IDataService" behaviorConfiguration="EndpBehavior" />

where binding is:
<bindings>
<webHttpBinding>
<binding name="WHB" crossDomainScriptAccessEnabled="true">
<security mode="None" />
</binding>
</webHttpBinding>
 </bindings>

and behaviorConfiguration is:
<endpointBehaviors>
<behavior name="EndpBehavior">
<webHttp/>
</behavior>
</endpointBehaviors>

Enjoy your service from Jquery html page!


No comments :

Post a Comment