b

Saturday, 26 October 2013

Create and consume Jsonp Service using WCF Rest Service

Create and consume Jsonp Service using WCF Rest Service

1) Create WCF Rest Service 

   Create a WCF Service Application

               Delete all existing files then add below files.

    1.1 ) Create a Data Contract called Person

     [DataContract]
    public class Person
    {
        [DataMember] public int id{get;set;}
        [DataMember] public String Name{get;set;}
        [DataMember] public DateTime Dob{get;set;}
    }

    1.2) Expose this using Service Contract

         [ServiceContract]
    interface Interface1
    {
        [WebGet(ResponseFormat=WebMessageFormat.Json)]
           
        Person GetPerson();
    }

1.3)  Implement this interface

namespace WcfService1
{
    [ServiceBehavior(IncludeExceptionDetailInFaults=true)]
    [JavascriptCallbackBehavior(UrlParameterName="$callback")]
[AspNetCompatibilityRequirements(RequirementsMode=AspNetCompatibilityRequirementsMode.Allowed)]
    public class Class1:Interface1
    {
        public Person GetPerson()
        {
            return new Person { id = 102, Dob = DateTime.Now.AddYears(-40), Name = "Peter"};
        }
    }
}

JavascriptCallbackBehavior Attribute specifies actual Callback parameter. in this case "callback"

1.4)  Enable Cross Domain Script Access in Web.config


<system.serviceModel>
    <bindings>
      <webHttpBinding>
        <binding name="mywebb" crossDomainScriptAccessEnabled="true">
         
        </binding>
      </webHttpBinding>
    </bindings>
    <services>
      <service name="WcfService1.Class1">
        <endpoint binding="webHttpBinding" bindingConfiguration="mywebb" contract="WcfService1.Interface1" behaviorConfiguration="restBehaviour"/>
      </service>
    </services>
    <behaviors>
      <endpointBehaviors>
        <behavior name="restBehaviour">
          <webHttp helpEnabled="true" faultExceptionEnabled="true"/>
        </behavior>
      </endpointBehaviors>
    </behaviors>
    <serviceHostingEnvironment aspNetCompatibilityEnabled="true" multipleSiteBindingsEnabled="true"/>
  </system.serviceModel>

1.5) Specify Host factory as WebServiceHostFactory in Service2.svc


<%@
    ServiceHost
    Factory="System.ServiceModel.Activation.WebServiceHostFactory"
    Service="WcfService1.Class1"
%>

1.6)Just Run the Service2.svc 

U will see help page and list of Operations


     
  

           
 

2) using javascript Consume Jsonp Rest Service

  2.1) Create a new Empty asp.net Web Application or Simply Html Page


2.2) Add a Callback function

              <script type="text/javascript">
                function fun1(persondata) {

                    alert("Name="+persondata.Name+
                           "Id=" + persondata.id+
                           "DOB=" + persondata.Dob);

                }

    </script>


2.3)  Call   WCF Service URL  using Script tag



<script type="text/javascript" src="http://localhost/WcfService1/Service2.svc/GetPerson?$callback=fun1"></script>

Just  run the web page

U will get

3) How to COnsume WCF REST jsonp service in JQUERY ajax

<script type="text/javascript">
     $(document).ready(function () {
     
         $.ajax({
             url: 'http://localhost/WcfService1/Service2.svc/GetPerson?$callback=localJsonpCallback',
             type: "GET",
             async: false,
             crossDomain: true,
             cache: false,
             jsonp: true,
             dataType: "jsonp",
         });
         //).done(function (data) {
         //    alert(data.Name);
         //}).fail(function (jqXHR, textStatus)
         //{
         //    alert(textStatus+jqXHR.status);
         //});
         //jsonpCallback: function (data) {
         //    alert(data + "callback");
         //}
    
     });
 </script>
    <script type="text/javascript">
        function localJsonpCallback(data) {
            alert(data.Name+" "+data.id+" "+data.Dob);
        }

    </script>

No comments:

Post a Comment