Friday, 13 December 2013

Callling WCF Rest service from cross domain

Hi all, i m happy to share some wcf idea today
i was having a problem in calling wcf service from the client ( my web page here ).
i searched a lot on net and at the end i found the solution.

The code is as below:

Interface: (eg. IService.cs)

[OperationContract]        
        [WebInvoke(Method = "GET", BodyStyle = WebMessageBodyStyle.Wrapped,
            UriTemplate = "/ReturnTime")]
        string ReturnTime();

Class: (eg. Service1.svc.cs)

The original signature of Method define in interface

public string ReturnTime()
        {
            return DateTime.Now.ToString();
        }

put this statement in top of the class
[AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)]


Web.congif

=> under <system.serviceModel> put the following
<bindings>
      <webHttpBinding>
        <binding name="webHttpBindingWithJsonP" crossDomainScriptAccessEnabled="true"></binding>
      </webHttpBinding>
      <basicHttpBinding>
        <binding name="AvailabilitySoap">
          <security mode="Transport" />
        </binding>
        <binding name="AvailabilitySoap1" />
      </basicHttpBinding>      
    </bindings>


=> under <services> put the following
<service name="HotelWcfService.ListRequest" behaviorConfiguration="ListRequestBehaviour">
        <endpoint address="" binding="webHttpBinding" contract="HotelWcfService.IListRequest" behaviorConfiguration="web"></endpoint>
      </service>

=> under <behaviors>

<behaviors>
      <endpointBehaviors>
        <behavior name="web">
          <webHttp defaultOutgoingResponseFormat="Xml" automaticFormatSelectionEnabled="true" />
        </behavior>
      </endpointBehaviors>
      <serviceBehaviors>
        <behavior name="ListRequestBehaviour">
          <serviceMetadata httpGetEnabled="true" />
          <serviceDebug includeExceptionDetailInFaults="false" />
        </behavior>
        <behavior name="">
          <serviceMetadata httpGetEnabled="true" />
          <serviceDebug includeExceptionDetailInFaults="false" />
        </behavior>
      </serviceBehaviors>
    </behaviors>

=> after <behaviors>
<serviceHostingEnvironment aspNetCompatibilityEnabled="true" multipleSiteBindingsEnabled="true" />


now add Global.asax file in your wcf service application solution.

and put the following code under Application_BeginRequest

HttpContext.Current.Response.AddHeader("Access-Control-Allow-Origin", "*");
            if (HttpContext.Current.Request.HttpMethod == "OPTIONS")
            {
                HttpContext.Current.Response.AddHeader("Cache-Control", "no-cache");
                HttpContext.Current.Response.AddHeader("Access-Control-Allow-Methods", "GET, POST");
                HttpContext.Current.Response.AddHeader("Access-Control-Allow-Headers", "Content-Type, Accept, x-requested-with");
                HttpContext.Current.Response.AddHeader("Access-Control-Max-Age", "1728000");
                HttpContext.Current.Response.End();
            }    

that's it for making wcf service ready to use.
now host the wcf service in local or web server to consume from the client.

now its time to write a javascript script to consume wcf service.

let me clear the two variable of json before writting the js code.

contentType means you are telling server that i am passing the data in this format.
dataType means you are expecting the data in this format from server.

To get the result in json format

<script type="text/javascript">
        $(document).ready(function () {

            $.ajax({
                type: "GET",
                url: "http://localhost:81/Service1.svc/ReturnTime",
                contentType: "application/json; charset=utf-8",
                dataType: "json",
                ProcessData: true,
                success: function (data) {
                    alert(data);
                },
                error: function (xhr) {
                    alert(xhr.responseText);
                }
            });
        });   
    
    </script>

To get the result in xml format

<script type="text/javascript">
        $(document).ready(function () {

            $.ajax({
                type: "GET",
                url: "http://localhost:81/Service1.svc/ReturnTime",
                contentType: "application/json; charset=utf-8",
                dataType: "xml",
                ProcessData: true,
                success: function (data) {
                    alert(data);
                },
                error: function (xhr) {
                    alert(xhr.responseText);
                }
            });
        });   
    
    </script>

Here i am requesting from json and getting the result in two format

just put this code on your web page and run the page.
you can see the result in firebug.

Hope you like this post and i wish it'll helpful to you.

Enjoy coading...

No comments:

Post a comment