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

WCF REST Service with JSON

By , 28 Feb 2012
 

While working with my client, I run into a problem with large file uploading using WCF-JSON. Here i am demonstrating the problem and solution through this article. The article also demonstrates step by step JSON communication using WCF.

Following are the experiments using WCF REST Service with JSON:

  • Invoking a method and getting string as return parameter
  • a string to method and getting class as return parameter
  • a class as method argument and receiving Boolean
  • large file as method argument

What is REST?

REST stands for Representational State Transfer and is an architectural style. It was developed in parallel with HTTP/1.1. In short REST is an architectural style that exploits the existing web protocols and technologies. REST provides an easier way of data access comparing with the SOAP protocol. REST and SOAP relies on HTTP protocol. While considering interoperability of WCF with other platforms like Android REST is considered to be a good solution.

REST provides an alternative to SOAP and WSDL. REST on Web Services has evolved in big numbers for the last few years. Thomas Roy Fielding, the principal author of HTTP specification described REST as the key architectural principle of World Wide Web.

One of the key characteristics of a RESTful Web service is the explicit use of HTTP methods (GET, POST, PUT, DELETE) in a way that follows the protocol as defined by RFC 2616. But in the case of SOAP, POST is used to achieve all the cases.

Examples are given below:

Method Description Example SOAP (WS-*) Equivalent
GET Retrieve an Item GET /books/101 POST endpointInvoke GetOrder(101);
POST Place an Item POST /books
<book>
<id>102</id>
<name>Book 2</name>
<author>Author 2</author>
<price>0</price>
</book>
POST endpointInvoke
InsertOrder(order);
PUT Modify an Item PUT /book/101 POST endpoint
Invoke UpdateOrder(order);
DELETE Delete an Item DELETE /books/101 POST endpoint
Invoke DeleteOrder(101);

Passing argument to the service through url makes the service invocation through browser address bar.

What is JSON?

JSON represents JavaScript Object Notation and is an open standard lightweight data interchange format in human readable form. Shortly, it is a data representation format.

JSON provides a simple alternative to the Fatty XML format of data representation. For example a class with properties name and age can be represented as:

{ 
    ”name”: ”Jack”, 
   “address”:”Number, Street”
    ”age”: 25
}

Advantages of WCF with JSON

WCF supports JSON formatting and we can achieve it by adding attributes to the operation contracts.

In the case of Web Services, the only protocol supported was SOAP. SOAP in turn relies on HTTP protocol. WCF supports more protocols and serves good advantage over Web Services. The System.Runtime.Serialization assembly contains the JSON formatters.

Applications Involved

There are 2 applications created for this article:

  • ServiceApp representing the service application with WCF, REST and JSON
  • ClientApp representing a windows application consuming the service

Before proceeding with the steps below, you need to create a solution with a WCF Service Application (ServiceApp) and Windows Forms Application (ClientApp). Now Add reference to System.Runtime.Serialization for the ClientApp.

The application contains code snippets for the following REST/JSON scenarios:

  • Invoking a method and getting string as return parameter
  • a string to method and getting class as return parameter
  • a class as method argument and receiving Boolean
  • large file as method argument

The solution explorer looks like below:

i1.jpg

Make sure you changed the startup projects to both of them in the solution properties.

i2.jpg

Replace the web.config of Service application with the following content of web.config attached.

Step 1: Receiving string through JSON

Create a new method in the IService interface as following:

[OperationContract]
[WebInvoke(Method="GET", UriTemplate="/GetData", RequestFormat=WebMessageFormat.Json,
           ResponseFormat=WebMessageFormat.Json)]
string GetData();


The above method returns one string on invoking. Implement the method in the Service class file as following:

public string GetData() 
{
    return "Data from Service";
}

On executing the application, we can invoke the method from the browser address bar itself using the url: http://localhost:11523/Service1.svc/GetData. We will be getting the Open With dialog box and opening in Notepad, we can see the string “Data from Service”.

The above invocation was through the browser. Inorder to access the content through a .Net application we have to do some additional amount of work.

  • Create WebClient instance
  • Format any parameters
  • Invoke the Method using Url
  • Unformat the received values


In the ClientApp create a button and on the click of it write the following code:

WebClient client = new WebClient();
byte[] data = client.DownloadData("http://localhost:11523/Service1.svc/GetData");
Stream stream = new MemoryStream(data);

DataContractJsonSerializer obj = new DataContractJsonSerializer(typeof(string));
string result = obj.ReadObject(stream).ToString();

MessageBox.Show(result);

On executing the application we can see the following result.
i3.jpg

Step 2: Receiving class through JSON

Now we can use the GET HTTP verb to return a Type using JSON. The input argument is an id in string. The method information is given below:

[OperationContract]
[WebInvoke(Method = "GET", UriTemplate = "/GetEmployee/{id}", 
          RequestFormat = WebMessageFormat.Json, ResponseFormat = WebMessageFormat.Json)]
Employee GetEmployee(string id);


Here we have to additional plumbing work to deserialize the received JSON Employee object. The code is given below:

DataContractJsonSerializer obj = new DataContractJsonSerializer(typeof(Employee));
Employee result = obj.ReadObject(stream) as Employee;

Step 3: Posting Typed Argument and returning Boolean

Here we are using the POST method to upload an Employee object. The service will be saving it and returning a Boolean.

[OperationContract]
[WebInvoke(Method = "POST", UriTemplate = "/SaveEmployee", 
           RequestFormat = WebMessageFormat.Json, ResponseFormat = WebMessageFormat.Json)]
bool SaveEmployee(Employee employee);

Step 4: Sending large file through JSON

Now we can try with sending file with JSON. The default endpoint behavior restricts maxReceivedSize as 65536. This does not allows larger file uploads. In our test application the endpoint behavior is modified to accommodate upto 2147483647 bytes of data. The sample application tests 10 MB file upload through REST and JSON formatting.

Modified Configuration

Following is the modified configuration section for the service part.

<webHttpBinding> 
        <binding name="StreamedRequestWebBinding"
                 bypassProxyOnLocal="true"
                 useDefaultWebProxy="false"
                 hostNameComparisonMode="WeakWildcard"
                 sendTimeout="10:15:00"
                 openTimeout="10:15:00"
                 receiveTimeout="10:15:00"
                 maxReceivedMessageSize="2147483647"
                 maxBufferSize="2147483647"
                 maxBufferPoolSize="2147483647"
                 transferMode="StreamedRequest">
          <readerQuotas maxArrayLength="2147483647"
                        maxStringContentLength="2147483647" />
        </binding>
 </webHttpBinding>

The configuration section has to be modified as the default WCF binding does not support large file size handling.

Client Application

Following is the screen shot for the Client application.

i4.jpg

Note


The REST/JSON service receiving code is not as friendly as the usual WCF service invocation code using Proxy. Still we can use Generics Methods to wrap the receiving code to make accessing the methods easier.

References

  • http://msdn.microsoft.com/en-us/library/ms730294.aspx
  • http://www.json.org/fatfree.html
  • http://debugmode.net/2011/05/15/wcf-rest-service-with-josn-data/
  • http://www.ibm.com/developerworks/webservices/library/ws-restful/
  • http://en.wikipedia.org/wiki/Roy_Fielding
  • http://myarch.com/json-pros-and-cons

Summary

In this article we have seen about the advantages of REST enabled WCF services along with examples. The JSON formatting was explored with string, class and large file uploading. Using the associated application you can see the actual service invocations for the above mentioned 4 scenarios.

Source Code

You can download the source code here.

License

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

About the Author

Jean Paul V.A
Architect
United States United States
Jean Paul is a Microsoft MVP and Architect with 12+ years of experience. He is very much passionate in programming and his core skills are SharePoint, ASP.NET & C#.
 
In the academic side he do hold a BS in Computer Science & MBA. In the certification side he holds MCPD & MCTS spanning from .Net Fundamentals to SQL Server.
 
Most of the free time he will be doing technical activities like researching solutions, writing articles, resolving forum problems etc. He believes quality & satisfaction goes hand in hand.
 
You can find some of his work over here. He blogs at http://jeanpaulva.com
Follow on   Twitter

Sign Up to vote   Poor Excellent
Add a reason or comment to your vote: x
Votes of 3 or less require a comment

Comments and Discussions

 
You must Sign In to use this message board.
Search this forum  
    Spacing  Noise  Layout  Per page   
GeneralMy vote of 5memberCoder.8629-May-13 2:58 
Nice Article and explained well.
GeneralMy vote of 5memberDBars18-May-13 13:16 
Clear and effective. Thanks
GeneralMy vote of 5professionalMohammed Hameed10-May-13 4:24 
Good stuff...
Question2 ProblemsmemberRomanopoly15-Apr-13 1:00 
Hi,
 
first of all many thanks for this very interesting example.
 
Than a problem I ran into:
 
I got a timeout trying to upload a file to the server from a remote client computer.
Maybe any advice how to solve it?
 
Kind Regards
 
Roman Pawlig
roman.pawlig@hotmail.com
AnswerRe: 2 ProblemsmvpJean Paul V.A27-Apr-13 4:48 
You can increase the default timeout value in web.config
 
Regards,
Jean Paul
Jean.

GeneralMy vote of 1memberBHazrati18-Mar-13 18:09 
Didn't get how the application is working
GeneralRe: My vote of 1memberRob Philpott30-Mar-13 11:21 
You didn't 'get it' and so gave the article the lowest possible score? Perhaps you should try something more simple, and let people who can 'get it' rate the article fairly.
Regards,
Rob Philpott.

GeneralMy vote of 5memberEvgeny Nikitin27-Feb-13 21:06 
You saved me quite a lot of time. Thanks!
GeneralRe: My vote of 5mvpJean Paul V.A28-Feb-13 1:02 
Thank You very much Nikitin for the good words!
Jean.

GeneralMy vote of 5memberАндрей Дотц25-Feb-13 20:59 
usefull
GeneralRe: My vote of 5mvpJean Paul V.A28-Feb-13 1:02 
Thank You my friend!
Jean.

Questionpass data from android to wcfmemberKrunal Rohit17-Feb-13 21:10 
as subject suggests, how to pass data from android client to wcf ??
QuestionA question about the "employee" classmemberEK77723-Jan-13 18:39 
hi!
Thank you for sharing this great code!
I got confused when I read the "employee" class. Where did you write the code to declare "employee" class? Using a tool?
 

THX
GeneralMy vote of 2memberMd. Humayun Rashed7-Jan-13 17:59 
where is the source code?
Questioncross web config changersin your sample codememberRizwan Riyaz Patel20-Nov-12 23:00 
could you please post cross domain web config changes in wcf
AnswerRe: cross web config changersin your sample codememberJean Paul V.A21-Nov-12 5:03 
Hello My Friend,
 
As I switched to SharePoint completely I cannot spare time to research on the cross domain problem.
 
Instead I can share some existing articles on the same:
 
http://www.codeproject.com/Articles/259832/Consuming-Cross-Domain-WCF-REST-Services-with-jQue
http://www.c-sharpcorner.com/uploadfile/dhananjaycoder/wcf-and-silverlight-with-cross-domain-isssue/
 
Regards,
Jean Paul
Jean.

GeneralRe: cross web config changersin your sample codememberRizwan Riyaz Patel22-Nov-12 4:49 
I already search the whole network for around three weeks but no Luck , What i understand is minor changes in web config, but the whole thing stops working altogether thanks any ways Dude Big Grin | :-D
QuestionCan u provide Perform All DML operations in DATABASE And also consume ASP.NET webpagesmemberMember 917112826-Jul-12 1:41 
Can u provide Perform All DML operations in DATABASE And also consume ASP.NET webpages,
plz help me simple example
AnswerRe: Can u provide Perform All DML operations in DATABASE And also consume ASP.NET webpagesmemberJean Paul V.A26-Jul-12 4:00 
Please find some samples for your reference:
DML – JSON Example
http://www.stonearticle.com/restful-aspnet-wcf--jquery---json-service-with-get-post-222-1.html

WCF Data Services (former ADO.NET Data Service) – I believe it is supporting JSON too
http://msdn.microsoft.com/en-us/data/odata.aspx
Jean.

GeneralMy vote of 4memberi_islamian16-Jul-12 2:31 
Nice one!
GeneralMy vote of 5memberkarrellavinayakrao21-Jun-12 6:59 
Its a good
Questionproblem calling GetDatamemberJinjer29-May-12 10:20 
with svc running in debug mode, replaced port# on http://localhost:11523/Service1.svc/GetData with my own, but get only "Webpage Cannot be Found". It's gotta be something simple, but I can't find it.
QuestionHow to add parameters?memberMember 74919427-Mar-12 5:10 
How to extend and call in step 3 the operation with additional parameters?
bool SaveEmployee(Employee employee, string username, string password);

GeneralMy vote of 3memberDean Oliver29-Feb-12 5:46 
no source code.
QuestionWhere can I download the code???membertompastom25-Feb-12 20:02 
?
AnswerRe: Where can I download the code???memberJean Paul V.A28-Feb-12 20:21 
I have updated the article with source link (at end)
Sorry for the delay in reply.
Jean.

QuestionFileInformation namespasememberMember 346072424-Feb-12 0:35 
Hi,
Thank you very much for this article.
 
I would like to ask about "FileInformation" namespace, as on file "MainForm.cs" line "71" as shown below:
======================================
66 private void button4_Click(object sender, EventArgs e)
67 {
68 WebClient client = new WebClient();
69 client.Headers["Content-type"] = "application/json";
70
71 FileInformation fileInfo = new FileInformation();
72 fileInfo.Name = "Test.txt";
73 fileInfo.Content = Get10MBFile();

74
75 MemoryStream stream = new MemoryStream();
76 DataContractJsonSerializer serializer = new DataContractJsonSerialize(typeof(FileInformation));
77 serializer.WriteObject(stream, fileInfo);
78
79 byte[] data = client.UploadData("http://localhost:11523/Service1.svc/UploadFile", "POST", stream.ToArray());
80
81 stream = new MemoryStream(data);
82 serializer = new DataContractJsonSerializer(typeof(int));
83 int result = (int)serializer.ReadObject(stream);
84
85 MessageBox.Show("Bytes in File: " + result.ToString());
86 }
==============================================
 
Whether "FileInformation" that you mean "FileInfo"?, if so, I can not find the content for "FileInformation.Name" and or "FileInformation.Content"
 
Please do advice
Regards,
thanks

AnswerRe: FileInformation namespasememberjinu.net24-Feb-12 3:45 
The origin of FileInformation is in the ServiceApp > IService1.cs
 
The file is created in client side on adding reference to the service.
(then it will reside in Reference.cs)
Jean.

GeneralMy vote of 1memberSelvin14-Feb-12 22:10 
WCF REST again ... and again not a REST ... wrong UriTemplates ...

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

Permalink | Advertise | Privacy | Mobile
Web03 | 2.6.130617.1 | Last Updated 29 Feb 2012
Article Copyright 2012 by Jean Paul V.A
Everything else Copyright © CodeProject, 1999-2013
Terms of Use
Layout: fixed | fluid