Click here to Skip to main content
Click here to Skip to main content

Retrieve Data From WCF Webservice using WCF RESTful Service and JSON

, 28 Apr 2014 CPOL
Rate this:
Please Sign up or sign in to vote.
Retrieve data From WCF Webservice using WCF RESTful service and JSON

Introduction to JSON

JSON stands for JavaScript Object Notation. It is lightweight data exchange format. It does not create lengthy tags like XML and produce human readable clean data. JSON is completely language independent. It gives you a collection of name/value pair. The data member names must be a valid JSON string and included in quotation marks or apostrophes.

Background

Introduction section of RESTful service, all the resource located in server side can be accessed using URL. Method exposed at the server side can be called using URL, to do that we need to decorate the service method with “WebGet” or “WebInvoke” attribute.

Using the Code

Let's discuss an example of retrieving the data from the WCF webservice, using WCF RESTful services and JSON. All the resources located in server side can be accessed using URL. Method exposed at the server side can be call using URL, to do that we need to decorate the service method with “WebGet” or “WebInvoke” attribute.

Create Employee DataContract for your RESTful Service

First create a [DataContract] class as mentioned below:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Runtime.Serialization;
 
namespace JSONWCF
{
 
    [DataContract]
    public class EmployeeContract
    {
        [DataMember]
        public string EmployeeID { get; set; }
 
        [DataMember]
        public string Employee_Name { get; set; }
 
        [DataMember]
        public string Employee_City { get; set; }
 
        [DataMember]
        public string Company_Name { get; set; }
 
        [DataMember]
        public string Employee_Salary { get; set; }
    }
} 

Create WCF RESTful Service

  • UriTemplate: The corresponding operation will be served with matching URI.
  • RequestFormat: Tells the format of request is XML or JSON.
  • ResponseFormat: Tells the format of response is XML or JSON
  • Method: WebInvoke has the method attribute. The value for this could be PUT, POST, DELETE. WebGet does not have this attribute as it is used only for http verb GET.

Create [ServiceContract] as IService which describes the [OperationContract] as mentioned below:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.ServiceModel.Web;
using System.ServiceModel;
namespace JSONWCF
{
    [ServiceContract]
    public interface IService
    {
        [OperationContract]
        [WebGet(UriTemplate = "/GetOEmployeeDetails/{EmployeeID}",
            RequestFormat = WebMessageFormat.Json,
            ResponseFormat = WebMessageFormat.Json)]
         EmployeeContract GetOEmployeeDetails(string EmployeeID);
    }
}

Now create the Service.svc to manage the WCF webservice operation as described below:

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

Now create Service.svc.cs to implement the ServiceContract's OperationContract Operation as below:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Data;
using System.Data.SqlClient;
 
namespace JSONWCF
{
    [Serializable]
    public class Service : IService
    {
        public EmployeeContract GetOEmployeeDetails(string EmployeeID)
        {
            EmployeeContract empDetails = new EmployeeContract();
            try
            {
                SqlConnection con = new SqlConnection();
                con.ConnectionString = "Data Source=.\\SQLEXPRESS;
                AttachDbFilename=C:\\Program Files (x86)\\Microsoft SQL Server\\
                MSSQL10.SQLEXPRESS\\MSSQL\\DATA\\OPERATIONS.mdf;
                Integrated Security=True;Connect Timeout=30;User Instance=True";
                con.Open();
                SqlCommand cmd = new SqlCommand("GetEmployeeDetails");
                cmd.CommandType = CommandType.StoredProcedure;
                cmd.Connection = con;
                cmd.Parameters.AddWithValue("@Employee_ID", EmployeeID);
                SqlDataAdapter adp = new SqlDataAdapter(cmd);
                DataSet ds = new DataSet();
                adp.Fill(ds);
                if (!(ds == null) && ds.Tables.Count > 0 && ds.Tables[0].Rows.Count > 0)
                {
               empDetails.EmployeeID = ds.Tables[0].Rows[0]["Employee_Id"].ToString();
               empDetails.Employee_Name = ds.Tables[0].Rows[0]["Employee_Name"].ToString();
               empDetails.Employee_City = ds.Tables[0].Rows[0]["Employee_City"].ToString();
               empDetails.Company_Name = ds.Tables[0].Rows[0]["Company_Name"].ToString();
               empDetails.Employee_Salary = ds.Tables[0].Rows[0]["Salary"].ToString();
                }
            }
            catch (Exception e)
            {
            }
            return empDetails;
        }        
    }
} 

Modify WCF Webservice's web.config as below:

WCF RESTful Service endpoint Configuration is about similar to normal endpoints.

<system.serviceModel>
<services>
            <service name="JSONWCF.Service" behaviorConfiguration="Default">
                <endpoint address="" binding="webHttpBinding" 
                behaviorConfiguration="webBehavior" contract="JSONWCF.IService">
                    <identity>
                        <dns value="localhost"/>
                    </identity>
                </endpoint>
                <endpoint address="mex" binding="mexHttpBinding" 
                contract="IMetadataExchange"/>
            </service>
        </services>
    <behaviors>
      <endpointBehaviors>
        <behavior name="webBehavior">
          <webHttp/>
        </behavior>
      </endpointBehaviors>
      <serviceBehaviors>
        <behavior name="Default">
          <serviceMetadata httpGetEnabled="true" />
        </behavior>
      </serviceBehaviors>
    </behaviors>
    </system.serviceModel>  

Now create a client application to consume the WCF web-service and retrieve the data using JSON.

View your OrderService

Right click on Service.svc and select View in browser. You may enter the below URL in browser:

<%@ Page Language="C#" AutoEventWireup="true" 
CodeFile="Home.aspx.cs" Inherits="Home" %>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
</head>
<body>
    <form id="form1" runat="server" enctype="multipart/form-data">
    <div>
        Employee ID :-<asp:Label ID="lblEmployeeID" runat="server"></asp:Label>
        <br />
        <br />
        Name of Employee :-<asp:Label ID="lblEmployeeName" runat="server"></asp:Label>
        <br />
        <br />
        City Name :-<asp:Label ID="lblEmployeecity" runat="server"></asp:Label>
        <br />
        <br />
        Company Name :-<asp:Label ID="lblcompany" runat="server"></asp:Label>
        <br />
        <br />
        Salary :-<asp:Label ID="lblsalary" runat="server"></asp:Label>
        <br />
        
    </div>
    </form>
</body>
</html> 

using System;  
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Net;
using System.IO;
using System.Runtime.Serialization.Json;
using client;
using System.Text;
using System.Data.SqlClient;
using System.Data;
public partial class Home:System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        try
        {
            string Employee_ID = "3456134";
            WebClient proxy = new WebClient();
            string serviceURL = string.Format
            ("http://localhost:49881/Service.svc/GetOEmployeeDetails/" + Employee_ID);
            byte[] data = proxy.DownloadData(serviceURL);
            Stream stream = new MemoryStream(data);
            DataContractJsonSerializer obj = new DataContractJsonSerializer(typeof(EmployeeContract));
            EmployeeContract empMaster = obj.ReadObject(stream) as EmployeeContract;
            lblEmployeeID.Text = empMaster.EmployeeID;
            lblEmployeeName.Text = empMaster.Employee_Name;
            lblEmployeecity.Text = empMaster.Employee_City;
            lblsalary.Text = empMaster.Employee_Salary;
            lblcompany.Text = empMaster.Company_Name;
        }
        catch (Exception ee)
        {
        }
    }   
}   

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

Share

About the Author

Dnyaneshwar@Pune
Software Developer
India India
No Biography provided

Comments and Discussions

 
GeneralMy vote of 1 PinmemberMember 1081357030-Jun-14 20:36 
QuestionGood tips for beginer Pinmembermahureamar28-Apr-14 2:55 
AnswerRe: Good tips for beginer PinmemberDnyaneshwar@Pune28-Apr-14 2:56 
AnswerRe: Good tips for beginer PinmemberJ. Wijaya28-Apr-14 17:58 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

| Advertise | Privacy | Terms of Use | Mobile
Web03 | 2.8.141220.1 | Last Updated 28 Apr 2014
Article Copyright 2014 by Dnyaneshwar@Pune
Everything else Copyright © CodeProject, 1999-2014
Layout: fixed | fluid