Wednesday, December 1, 2010

Steps to Call WCF Service using jQuery

Shout it kick it on DotNetKicks.com
Download Code

This article illustrates how to call Windows Communication Foundation (WCF) services from your jQuery client code, and points out where special care is needed. Before you start reading and following this article, first read this blog entry which describes how to create a WCF service: Create, Host(Self Hosting, IIS hosting) and Consume WCF servcie

Step 1

Once you are done with creating the WCF service, you need to specify the attributes on the server type class for ASP.NET  Compatibility mode, so that the WCF service works as a normal ASMX service and supports all existing ASP.NET features. By setting compatibility mode, the WCF service will have to be hosted on IIS and communicate with its client application using HTTP.

Read more about this in detail here: WCF Web HTTP Programming Object Model

Following line of code set ASP.NET Compatibility mode
[AspNetCompatibilityRequirements(RequirementsMode =
            AspNetCompatibilityRequirementsMode.Allowed)]
public class Service : IService
{
    //  .....your code
}

Service.Cs
[AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)]
public class Service : IService
{
    public string GetData(int value)
    {
        return string.Format("You entered: {0}", value);
    }


    public string[] GetUser(string Id)
    { return new User().GetUser(Convert.ToInt32(Id)); }
}

public class User
{

    Dictionary<int, string> users = null;
    public User()
    {
        users = new Dictionary<int, string>();
        users.Add(1, "pranay");
        users.Add(2, "Krunal");
        users.Add(3, "Aditya");
        users.Add(4, "Samir");
    }

    public string[] GetUser(int Id)
    {
        var user = from u in users
                   where u.Key == Id
                   select u.Value;

        return user.ToArray<string>();
    }

}

Step 2

Next you need to specify attributes at operation level in the service contract file for each method or operation. To do this, decorate the method with WebInvoke, which marks a service operation as one that responds to HTTP requests other than GET. Accordingly, your operational level code in the contract file will be as follows:

[OperationContract]
    [OperationContract]
    [WebInvoke(Method = "POST", 
BodyStyle = WebMessageBodyStyle.Wrapped, 
ResponseFormat = WebMessageFormat.Json)]
    string[] GetUser(string Id);

As you can see in the code, sub-attributes having values to support calling via jQuery are marked with Method=post, so data gets posted to the service via a POST method.

ResponseFormat = WebMessaeFormat Json indicate data return as json format.

IService.cs
[ServiceContract]
public interface IService
{
    [OperationContract]
    [WebInvoke(Method = "GET",
     ResponseFormat = WebMessageFormat.Json)]
    string GetData(int value);

    [OperationContract]
    [WebInvoke(Method = "POST", BodyStyle = WebMessageBodyStyle.Wrapped, ResponseFormat = WebMessageFormat.Json)]
    string[] GetUser(string Id);
}

Step 3

You need to change the default configuration created by Visual Studio in Web.Config file for WCF services, so that it works with the HTTP protocol request send by jQuery client code.

<system.serviceModel>
  <behaviors>
   <serviceBehaviors>
    <behavior name="ServiceBehavior">
     <serviceMetadata httpGetEnabled="true"/>
     <serviceDebug includeExceptionDetailInFaults="true"/>
    </behavior>
   </serviceBehaviors>
   <endpointBehaviors>
    <behavior name="EndpBehavior">
     <webHttp/>
    </behavior>
   </endpointBehaviors>
  </behaviors>
  <services>
   <service behaviorConfiguration="ServiceBehavior" name="Service">
    <endpoint address="" binding="webHttpBinding" contract="IService" behaviorConfiguration="EndpBehavior"/>
   </service>
  </services>
</system.serviceModel>


As you can see in above config file, the EndPoint setting is changed, and EndPointBehaviors added to support WEBHTTP requests.

Note :
Endpoint settings done in the config works in conjunction with the WebInvoke attribute of the operation and the compatibility attribute set in ServiceType to support HTTP requests sent by jQuery.

Step 4

To consume web service using jQuery i.e to make call to WCF service you either use jQuery.ajax() or jQuery.getJSON(). For this I am using jQuery.ajax() method

To set the request, first define a variable. This will be helpful when you are calling multiple methods and creating a different js file to call the WCF service.

<script type="text/javascript">
         var Type;
         var Url;
         var Data;
         var ContentType;
         var DataType;
         var ProcessData;

The following function initializes variables which are defined above to make a call to the service.

function WCFJSON() {
             var userid = "1";
             Type = "POST";
             Url = "Service.svc/GetUser";
             Data = '{"Id": "' + userid + '"}';
             ContentType = "application/json; charset=utf-8";
             DataType = "json"; varProcessData = true; 
             CallService();
         }

CallService function sent request to service by setting data in $.ajax

         //function to call WCF  Service       
         function CallService() {
             $.ajax({
                 type: Type, //GET or POST or PUT or DELETE verb
                 url: Url, // Location of the service
                 data: Data, //Data sent to server
                 contentType: ContentType, // content type sent to server
                 dataType: DataType, //Expected data format from server
                 processdata: ProcessData, //True or False
                 success: function(msg) {//On Successfull service call
                     ServiceSucceeded(msg);
                 },
                 error: ServiceFailed// When Service call fails
             });
         }

         function ServiceFailed(result) {
             alert('Service call failed: ' + result.status + '' + result.statusText);
             Type = null; varUrl = null; Data = null; ContentType = null; DataType = null; ProcessData = null;
         }

Note:
The following code checks the result.GetUserResult statement, so your result object gets the property your service method name + Result. Otherwise, it will give an error like object not found in Javascript.

         function ServiceSucceeded(result) {

             if (DataType == "json") {

                 resultObject = result.GetUserResult;
               
                 for (i = 0; i < resultObject.length; i++) {
                     alert(resultObject[i]);
                 }
            
             }
        
         }

         function ServiceFailed(xhr) {
             alert(xhr.responseText);
             if (xhr.responseText) {
                 var err = xhr.responseText;
                 if (err)
                     error(err);
                 else
                     error({ Message: "Unknown server error." })
             }
             return;
         }

 $(document).ready(
         function() {
         WCFJSON();
         }
         );
</script>

Summary

It is easy to call a WCF service from your client code you; just need to set your WCF service to serve requests through the HTTP protocol and set your client to consume it via the HTTP protocol.

23 comments:

  1. I love pranayamr.blogspot.com! Here I always find a lot of helpful information for myself. Thanks you for your work.
    Webmaster of http://loveepicentre.com and http://movieszone.eu
    Best regards

    ReplyDelete
  2. gets unsupported media type error. Any idea what is causing that?

    ReplyDelete
  3. hi pranayamr.blogspot.com-ers all the best to you all - matty

    ReplyDelete
  4. Could you upload your source code to github or something like that?, rapidshare link died .

    Thanks.

    ReplyDelete
    Replies
    1. you can find article with same name on the code project site where you can also find code to download

      Delete
  5. you can find article with same name on the code project site where you can also find code to download

    ReplyDelete
  6. Hey,
    I am having some trouble in fetching JSON string from WCF Service via JQuery.

    http://stackoverflow.com/questions/9546338/unable-to-return-json-string-from-wcf-service-from-jquery#comment12097852_9546338

    Please help.

    ReplyDelete
  7. Hey,
    Please I am also having some trouble in getting this working.

    http://stackoverflow.com/questions/10062425/unable-to-access-wcf-function-getting-error-405-method-not-allowed

    ReplyDelete
  8. you can find article with same name on the code project site where you can also find code to download

    ReplyDelete
  9. How i can consume restful wcf service with https using jquery

    ReplyDelete
    Replies
    1. here is the thing you wnat : http://pranayamr.blogspot.com/2011/03/rest.html

      Delete
  10. The jquery code that consumes the wcf service fails to execute the ajax call.
    function CallService() {
    $.ajax({
    type: Type, //GET or POST or PUT or DELETE verb
    url: Url, // Location of the service
    data: Data, //Data sent to server
    contentType: ContentType, // content type sent to server
    dataType: DataType, //Expected data format from server
    processdata: ProcessData, //True or False
    success: function(msg) {//On Successfull service call
    ServiceSucceeded(msg);
    },
    error: ServiceFailed// When Service call fails
    });
    }

    ReplyDelete
    Replies
    1. As soon as the breakpoint hits the line where it says "success: function(msg) {//On Successfull service call" the error is thrown saying "NetworkError: 405 Method Not Allowed"

      Delete
  11. Is it possible to call this same service (using JQuery) if it was HTTPS requiring client certificates? How can you attach the client certificate?

    Thanks for any help.

    ReplyDelete
  12. boss code to upload kar do .there is no code on rapidshare .your code is moved on

    ReplyDelete
  13. Gud Post. I have one question. I using some different Artitecture like
    1)Data(My EDMX Model)
    2)Service (WCF Service)
    3)BL(Bussiness Logic)
    4) UI (Front END) here i give the Service Reference of my service.
    so throught this i can consume my service in the .cs Page .
    My question is how to consume service in .aspx Page(Javascript).

    Everywhere i see In one solution all is happing.

    Thanks

    ReplyDelete
  14. Hello, i think that i saw you visited my web site so i came to
    “return the favor”.I'm trying to find things to improve my site!I suppose its ok to use some of your ideas!!

    Feel free to surf to my weblog: pharmacy tech schools

    ReplyDelete
  15. It's great that you are getting thoughts from this article as well as from our dialogue made at this time.

    http://animalmundimodapet.com.br/how-buy-real-followers-twitter-any-benefits
    http://amthvac.com/drupal/node/18601
    http://anairhostess.com/real-world-support-designed-social-media-services-and-marketing-necessities
    http://anairhostess.com/recognize-twitter-and-consequence-get-twitter-followers
    http://amherstblock.com/index.php?do=/blog/76532/bucketlist-trends-in-great-ammounts-onto-twitter/

    Feel free to surf to my web-site; exceptional

    ReplyDelete
  16. hi, Great article, but this only works in IE in Chrome or Mozilla the ServiceFailed javascript method is fired.

    ReplyDelete
  17. Hi, you can try the below link as well, It worked for me -

    http://vsstack.blogspot.in/2013/06/wcf-from-jquery.html

    ReplyDelete
  18. do you know how to invoke wcf service from java code?

    ReplyDelete