WCF REST Service With JOSN Data


In this article I will show how to work with the WCF REST Service with JOSN type of Data.  I will discuss both POST and GET operation using the JOSN data type. 

Creating Service 

I have written many articles about creating a basic WCF REST Service.  Please refer to them if required. 

WebGet Method

Let us create a Get method in a WCF REST Service returning a JOSN type of data. To return a JSON type of data from a WCF REST Service, we need to explicitly define the message format as JOSN in WebGet:

WCFRESTwithJOSN1.jpg
 
In the above GetMessageasJSON service: 
  1. RequestFormat is of JOSN type
  2. ResponseFormat is of JSON type. 
  3. Above method is returning a string. 
WebInvoke Method

Create one more method in the WCF REST Service to POST JOSN data: 

WCFRESTwithJOSN2.jpg 

In above GetMessageasJSON service 
  1. RequestFormat is of JOSN type 
  2. ResponseFormat is of JSON type. 
  3. Above method is returning an object of custom class Student. 
  4. Method is POST 
  5. Input parameter is an object of custom class Student.
Student is a custom class and should be exposed as a Data Contract.  At the client side all the custom classes can be distributed as a separate dll. 

Eventually the Service and Student classes are as below: 

IService1.cs

using System;
using System.ServiceModel;
using System.ServiceModel.Web;
using System.Runtime.Serialization; 
namespace JQueryWCFREST
{
    [ServiceContract]
    public interface IService1
    {
        [OperationContract]
        [WebGet(UriTemplate="/GetJOSNMessage",
            RequestFormat=WebMessageFormat.Json,
            ResponseFormat=WebMessageFormat.Json)]
        String GetMessageasJSON();
        [OperationContract]
        [WebInvoke(UriTemplate = "/UplaodData"
                  Method = "POST",
                   RequestFormat = WebMessageFormat.Json,
                   ResponseFormat = WebMessageFormat.Json)]
        Student GetUpdatedStudent(Student s);
    }
    [DataContract]
    public class Student
    {
        [DataMember]
        public string RollNumber { getset; }
        [DataMember
        public string Name { getset; }
    }
}

The Service implementation is as below: 

Service1.svc.cs

using System;
namespace JQueryWCFREST
{
    public class Service1 : IService1
    {
        public String GetMessageasJSON()
        {
            return "Hi , I am JOSN DATA "
        }
        public Student GetUpdatedStudent(Student s)
        {
            s.Name = "I have Updated Student Name";
            return s; 
        }
    }
}

Hosting Service
 
The hosting of a JOSN WCF REST Service can be done in exactly the same way as a default XML WCF REST Service. 

Consuming Service 

To call the above service from ASP.Net or any Managed application, we will have to use the following references.  

WCFRESTwithJOSN3.jpg
 
Performing Get Operation 

At the client side the usual download of data with WebClient will do the work.  To de-serialize the data, we can use DataContractJSONSerializer:

WCFRESTwithJOSN4.jpg
 
In the above method: 
  1. Data is being downloaded as stream using WebClient 
  2. De-serialized data is using DataContractJSONSerializer 
Performing POST Operation 

WCFRESTwithJOSN5.jpg
 
In the above method: 
  1. POST operation is being performed using WebClient 
  2. Data is being serialized  to JOSN type using DataContractJsonSeeializer
For reference the client side code to perform the operation against a JSON type WCF REST Service is as below: 

Program.cs 

using System;
using System.Net;
using System.IO;
using System.Runtime.Serialization.Json;
using JQueryWCFREST;

namespace JSONClient
{
    class Program
    {
        static void Main(string[] args)
        {
            #region Getting JOSN Data 
            WebClient proxy = new WebClient();
            byte[] data = proxy.DownloadData("http://localhost:38395/Service1.svc/GetJosnmessage");
            Stream stream = new MemoryStream(data);
            DataContractJsonSerializer obj = new DataContractJsonSerializer(typeof(string));
            string result = obj.ReadObject(stream).ToString();
            Console.WriteLine(result.ToString());
            Console.ReadKey(true);
            #endregion 
            #region Uploading JOSN Data 
            Student student = new Student{Name ="Dhananjay",RollNumber ="9"};          
            WebClient Proxy1 = new WebClient();
            Proxy1.Headers["Content-type"] = "application/json";
            MemoryStream ms = new MemoryStream();
            DataContractJsonSerializer serializerToUplaod = new DataContractJsonSerializer(typeof(Student));
            serializerToUplaod.WriteObject(ms, student);
            data = Proxy1.UploadData("http://localhost:38395/Service1.svc/UplaodData""POST", ms.ToArray());
            stream = new MemoryStream(data);
            obj = new DataContractJsonSerializer(typeof(Student));
            var resultStudent = obj.ReadObject(stream) as Student;
            Console.WriteLine(resultStudent.RollNumber+" " + resultStudent.Name);
            Console.ReadKey(true);
            #endregion 
        }
    }
}

On running the expected output is:  

WCFRESTwithJOSN6.jpg

Up Next
    Ebook Download
    View all
    Learn
    View all