Search...

Wednesday, May 1, 2013

REST based services in WCF

Consuming cross-domain WCF REST services with Jquery using JSON


Download

Step 1: 

Create a solution with three projects.
1. ServiceLibrary (WCF Service Library)
2. Host (WCF Service Application)
3. Client (ASP.NET Empty Web Application)


Step 2:

Modify the app.config, IService.cs and Service.cs as follows in ServiceLibrary application.


<?xml version="1.0"?>
<configuration>

  <system.web>
    <compilation debug="true"/>
    <authentication mode="None"/>
  </system.web>

  <system.serviceModel>
    <services>
      <service name="ServiceLibrary.Service1" behaviorConfiguration="DefaultBehavior">
        <host>
          <baseAddresses>
            <add baseAddress="http://localhost:8080/service"/>
          </baseAddresses>
        </host>
        <endpoint address="basic" binding="basicHttpBinding" contract="ServiceLibrary.IService1"/>
        <endpoint address="mex" binding="mexHttpBinding" contract="IMetadataExchange"/>
      </service>
    </services>
 
    <behaviors>
      <serviceBehaviors>
        <behavior name="DefaultBehavior">
          <serviceMetadata httpGetEnabled="true"/>
          <serviceDebug/>
        </behavior>
      </serviceBehaviors>
    </behaviors>
  </system.serviceModel>

  <startup>
    <supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.0"/>
  </startup>
</configuration>

**********************************************************************

using System.Runtime.Serialization;
using System.ServiceModel;
using System.ServiceModel.Web;

namespace ServiceLibrary
{
    [ServiceContract]
    public interface IService1
    {
        [OperationContract(Name="GetSample")]
        [WebInvoke(Method="GET", UriTemplate = "GetSample?value={value}", RequestFormat = WebMessageFormat.Json, ResponseFormat = WebMessageFormat.Json)]
        string GetData(string value);

        [OperationContract(Name="PostSample")]
        [WebInvoke(Method = "POST", UriTemplate = "PostSample/compositeType", RequestFormat = WebMessageFormat.Json, ResponseFormat = WebMessageFormat.Json)]
        CompositeType GetDataUsingDataContract(CompositeType compositeType);
    }

    [DataContract]
    public class CompositeType
    {
        bool boolValue = true;
        string stringValue = "Hello ";

        [DataMember]
        public bool BoolValue
        {
            get { return boolValue; }
            set { boolValue = value; }
        }

        [DataMember]
        public string StringValue
        {
            get { return stringValue; }
            set { stringValue = value; }
        }
    }
}

**********************************************************************

using System;
using System.ServiceModel.Activation;

namespace ServiceLibrary
{
    [AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)]
    public class Service1 : IService1
    {
        public string GetData(String value)
        {
            return String.Format(value);
        }

        public CompositeType GetDataUsingDataContract(CompositeType compositeType)
        {
            return compositeType;
        }
    }
}

**********************************************************************

Step 3:

Do following in Host application.
1. Delete IService1.cs
2. Rename Service1.svc to Service.svc 
3. Open Service.svc and update it as follows

<%@ ServiceHost Language="C#" Debug="true" Service="ServiceLibrary.Service1" CodeBehind="ServiceLibrary.Service1.cs"  %>

4. Select Host application press mouse right click select Add Reference.. navigate to project and select ServiceLibrary and press ok.

5. Select Host application press mouse right click select Add New Item..add Global.asax file in project and update it as follows

protected void Application_BeginRequest(object sender, EventArgs e)
        {
            HttpContext.Current.Response.AddHeader("Access-Control-Allow-Origin", "*");

            if (HttpContext.Current.Request.HttpMethod == "OPTIONS")
            {
                HttpContext.Current.Response.AddHeader("Access-Control-Allow-Methods", "GET,POST");
                HttpContext.Current.Response.AddHeader("Access-Control-Allow-Headers", "Content-Type, Authorization, Accept");
                HttpContext.Current.Response.End();
            }
        }

6.  Open Web.config and update it as follows


<?xml version="1.0"?>
<configuration>

  <system.web>
    <compilation debug="true" targetFramework="4.0"/>
    <authentication mode="None"/>
  </system.web>
  <system.serviceModel>

    <services>
      <service behaviorConfiguration="DefaultBehavior" name="ServiceLibrary.Service1">
        <endpoint address="json" binding="webHttpBinding" behaviorConfiguration="JsonBehavior" bindingConfiguration="webHttpBindingWithJsonP" contract="ServiceLibrary.IService1"/>
      </service>
    </services>

    <bindings>
      <webHttpBinding>
        <binding name="webHttpBindingWithJsonP"
                 crossDomainScriptAccessEnabled="true" >
        </binding>
      </webHttpBinding>
    </bindings>
 
    <behaviors>
      <endpointBehaviors>
        <behavior name="JsonBehavior">
          <webHttp helpEnabled="true" defaultOutgoingResponseFormat="Json" />
        </behavior>
      </endpointBehaviors>
      <serviceBehaviors>
        <behavior name="DefaultBehavior">
          <serviceMetadata httpGetEnabled="true" />
          <serviceDebug includeExceptionDetailInFaults="false" />
        </behavior>
        <behavior name="">
          <serviceMetadata httpGetEnabled="true" />
          <serviceDebug includeExceptionDetailInFaults="false" />
        </behavior>
      </serviceBehaviors>
    </behaviors>

    <serviceHostingEnvironment aspNetCompatibilityEnabled="true"
      multipleSiteBindingsEnabled="true"/>
 
    <standardEndpoints>
      <webScriptEndpoint>
        <standardEndpoint crossDomainScriptAccessEnabled="true"/>
      </webScriptEndpoint>
      <webHttpEndpoint>
        <standardEndpoint name="" helpEnabled="true" automaticFormatSelectionEnabled="true"/>
      </webHttpEndpoint>
    </standardEndpoints>

  </system.serviceModel>
 
</configuration>

7. Create a folder in Win Drive:\inetpub\wwwroot\RestService

8. Press (Win key) + R type inetmgr press enter.

9. Navigate to RestService press mouse right clickselect Convert To Application.

10. Select Host application press mouse right click select publish..


**********************************************************************

Step 4:

Do following in Client application.
1. Download the latest jquery library from http://jquery.com/download/
2. Select Client application press mouse right click select Add New Item..add a Web Form and update it as follows.

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
    <script src="Scripts/jquery-1.4.1.min.js" type="text/javascript"></script>
</head>
<body>
    <form id="form1" runat="server">
    <div>
    </div>
    </form>
</body>
</html>
<script type="text/javascript">
    var json = {BoolValue: true,StringValue: "Hellow World !"};
    json = JSON.stringify(json);

    $(document).ready(function () {

        document.writeln(json + "<br/>");

        $.ajax({
            cache:false,
            url: 'http://localhost/RestService/Service.svc/json/GetSample?value=abcd',
            type: "GET",
            dataType: "json",
            contentType: "application/json; charset=utf-8",
            crossDomain: true,
            success: function (response) {
               alert("GET " + response);
            },
            error: function (xhr) {
                document.writeln("error");
            }
        });

        $.ajax({
            cache: false,
            url: 'http://localhost/RestService/Service.svc/json/PostSample/compositeType',
            data: json,
            processData: true,
            type: "POST",
            dataType: "json",
            contentType: "application/json; charset=utf-8",
            crossDomain: true,
            success: function (response) {
                alert("BoolValue: " + response.BoolValue + " StringValue: " + response.StringValue);
            },
            error: function (xhr) {
                document.writeln("error");
            }
        });

    });
</script>

**********************************************************************

Step 5:

Select Client application and set it as a Start Up project and run the application if every thing goes well you will get following response.

  1. Request URL:
    http://localhost/RestService/Service.svc/json/PostSample/compositeType
  2. Request Method:
    POST
  3. Status Code:
    200 OK
  4. Request Headersview source
    1. Accept:
      application/json, text/javascript, */*
    2. Accept-Charset:
      ISO-8859-1,utf-8;q=0.7,*;q=0.3
    3. Accept-Encoding:
      gzip,deflate,sdch
    4. Accept-Language:
      en-US,en;q=0.8
    5. Connection:
      keep-alive
    6. Content-Length:
      48
    7. Content-Type:
      application/json; charset=UTF-8
    8. DNT:
      1
    9. Host:
      localhost
    10. Origin:
      http://localhost:60412
    11. Referer:
      http://localhost:60412/
    12. User-Agent:
      Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.31 (KHTML, like Gecko) Chrome/26.0.1410.64 Safari/537.31
  5. Request Payloadview source
    {BoolValue:true, StringValue:Hello World !}
    1. BoolValuetrue
    2. StringValue"Hello World !"
    1. Response Headersview source
      1. Access-Control-Allow-Origin:
        *
      2. Cache-Control:
        private
      3. Content-Length:
        48
      4. Content-Type:
        application/json; charset=utf-8
      5. Date:
        Wed, 01 May 2013 17:46:40 GMT
      6. Server:
        Microsoft-IIS/7.5
      7. Set-Cookie:
        ASP.NET_SessionId=m2gaoombumrilv5juh3dimha; path=/; HttpOnly
      8. X-AspNet-Version:
        4.0.30319
      9. X-Powered-By:
        ASP.NET

    And

    1. Request URL:
      http://localhost/RestService/Service.svc/json/GetSample?value=Hello%20World%20!&_=1367430400381
    2. Request Method:
      GET
    3. Status Code:
      200 OK
    4. Request Headersview source
      1. Accept:
        application/json, text/javascript, */*
      2. Accept-Charset:
        ISO-8859-1,utf-8;q=0.7,*;q=0.3
      3. Accept-Encoding:
        gzip,deflate,sdch
      4. Accept-Language:
        en-US,en;q=0.8
      5. Connection:
        keep-alive
      6. Content-Type:
        application/json; charset=utf-8
      7. DNT:
        1
      8. Host:
        localhost
      9. Origin:
        http://localhost:60412
      10. Referer:
        http://localhost:60412/
      11. User-Agent:
        Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.31 (KHTML, like Gecko) Chrome/26.0.1410.64 Safari/537.31
    5. Query String Parametersview sourceview URL encoded
      1. value:
        Hello World !
      2. _:
        1367430400381
    6. Response Headersview source
      1. Access-Control-Allow-Origin:
        *
      2. Cache-Control:
        private
      3. Content-Length:
        15
      4. Content-Type:
        application/json; charset=utf-8
      5. Date:
        Wed, 01 May 2013 17:46:40 GMT
      6. Server:
        Microsoft-IIS/7.5
      7. Set-Cookie:
        ASP.NET_SessionId=gxoaqee24pubj0jt0qhc4cul; path=/; HttpOnly
      8. X-AspNet-Version:
        4.0.30319
      9. X-Powered-By:
        ASP.NET



    No comments: