Click here to Skip to main content
Click here to Skip to main content
Technical Blog

Tagged as

Creating and consuming a RESTful service using WCF and JavaScript

, 17 Jul 2014 CPOL
Rate this:
Please Sign up or sign in to vote.
REST !! REST !! REST !! It’s the buzz word recently with the advent of mobile revolution. You know what’s more worse than not having heard about a Buzz word!! Its having heard about it, but having no idea of its implications or practical implementation. Sometime back I blogged about how

REST !! REST !! REST !!

It’s the buzz word recently with the advent of mobile revolution. You know what’s more worse than not having heard about a Buzz word!! Its having heard about it, but having no idea of its implications or practical implementation.

Sometime back I blogged about how easy Microsoft has made it to create a RESTful web service using ASP.NET WebApi.

But what about people who are stuck with .NET 3.5 or just are unwilling to skill up from what they have learned in WCF due to sheer inertia. Well, I have discovered recently that it has always been possible to create RESTful web service using WCF. I stumbled upon the need to create a RESTful service in WCF because I had to use .Net 3.5, so I wasn’t possible to use ASP.NET WebApi. And I’m glad that I did. J

I discovered that creating a RESTful service in WCF is not that different from creating a normal WCF service. Of course the only problem I have with WCF is that its just too much abstracted from the inner workings of a RESTful service or how the Web works in general. This can actually cause quite a bit of a discomfort in the event that we get stuck at a technical challenge and we are unable to figure out what it happening because we have no idea what is happening underneath the layers of WCF.

So, if we want to make a WCF service RESTful, these are the below things which need to be addressed:

  1. Decorate our operation contracts with a WebInvoke or a WebGet attribute.
  2. Use webHttpBinding in our config file (since it has to respond to Http verbs)

That’s it. Voila!! So let’s get started :

Consider the below Service Contract Interface of a service which we are creating:

[ServiceContract]
public interface IRestServ
{
[OperationContract]
[WebInvoke(Method = "GET", ResponseFormat = WebMessageFormat.Json, BodyStyle = WebMessageBodyStyle.Wrapped, UriTemplate = "json/names")]
List<string> GetNames();
 
[OperationContract]
[WebInvoke(Method = "GET", ResponseFormat = WebMessageFormat.Json, BodyStyle = WebMessageBodyStyle.Wrapped, UriTemplate = "json/names/{lastname}")]
List<string> GetNamesByLastName(string lastname);
 
[OperationContract]
[WebInvoke(Method = "POST", RequestFormat = WebMessageFormat.Json, ResponseFormat = WebMessageFormat.Json, BodyStyle = WebMessageBodyStyle.Bare, UriTemplate = "json/save")]
bool SaveNames(List<string> lstRecords);
}

A few thing to notice in the above piece of code:

  1. WebInvoke attribute is actually something which indicates that the service can be invoked from a client side script such as JavaScript
  2. The Method parameter indicates which Http verb will the operation respond to
  3. The Response format defines the format of the response which the operation will return (It could be Json as well as Xml)
  4. The BodyStyle indicates whether the parameters sent to and from the client side will be wrapped in the request or written directly to the body (Wrapped or Bare). There a couple of more options which you could try out here.
  5. The Uril template actually defines the format of URL string which needs to be invoked from client side

The corresponding service code would be as below :

public class RestServ : IRestServ 
{
public List<string> GetNames()
{
List<string> lst = new
List<string>() { &ldquo;Ram Kumar&rdquo;, &ldquo;Shyam Kumar&rdquo;, &ldquo;Laxman Prasad&rdquo;, &ldquo;Ram Prasad&rdquo; };
return lst;
}

public List<string> GetNamesByLastName(string lastname)
{
List<string> lst = new
List<string>() { &ldquo;Ram Kumar&rdquo;, &ldquo;Shyam Kumar&rdquo;, &ldquo;Laxman Prasad&rdquo;, &ldquo;Ram Prasad&rdquo; };
return lst.Where(n=>n.Contains(lastname)).ToList();
}

public bool SaveNames(List<string> lstRecords)
{
//Save the list of names somewhere
return true;
}
}

Now, we just need to make a few changes to our web.config in terms of defining the binding for our WCF service.

<system.serviceModel>
<bindings>
<webHttpBinding>
<binding
name=&ldquo;MyWcfRestService.WebHttp&ldquo;
maxBufferSize=&ldquo;2147483647&ldquo;
maxBufferPoolSize=&ldquo;2147483647&ldquo;
maxReceivedMessageSize=&ldquo;2147483647&ldquo;
transferMode=&ldquo;Streamed&ldquo;
sendTimeout=&ldquo;00:05:00&ldquo;>
<readerQuotas
maxDepth=&ldquo;2147483647&ldquo;
maxStringContentLength=&ldquo;2147483647&ldquo;
maxArrayLength=&ldquo;2147483647&ldquo;
maxBytesPerRead=&ldquo;2147483647&ldquo;
maxNameTableCharCount=&ldquo;2147483647&ldquo;/>
<security
mode=&ldquo;None&ldquo; />
</binding>
</webHttpBinding>
</bindings>
<services>
<service
behaviorConfiguration=&ldquo;MyWcfRestService.RestServBehavior&ldquo;
name=&ldquo;MyWcfRestService.RestServ&ldquo;>
<endpoint
address=&ldquo;&rdquo;
behaviorConfiguration=&ldquo;web&ldquo;
binding=&ldquo;webHttpBinding&ldquo;
bindingConfiguration=&ldquo;MyWcfRestService.WebHttp&ldquo;
contract=&ldquo;MyWcfRestService.IRestServ&ldquo;>
<identity>
<dns
value=&ldquo;localhost&ldquo; />
</identity>
</endpoint>
<endpoint
address=&ldquo;mex&ldquo;
binding=&ldquo;mexHttpBinding&ldquo;
contract=&ldquo;IMetadataExchange&ldquo; />
</service> 
</services>
<behaviors>
<endpointBehaviors>
<behavior
name=&ldquo;web&ldquo;>
<webHttp />
</behavior>
</endpointBehaviors>
<serviceBehaviors>
<behavior
name=&ldquo;MyWcfRestService.RestServBehavior&ldquo;>
<serviceMetadata
httpGetEnabled=&ldquo;true&ldquo; />
<serviceDebug
includeExceptionDetailInFaults=&ldquo;true&ldquo; />
</behavior> 
</serviceBehaviors>
</behaviors>
</system.serviceModel>

A few things to note from the above:

  1. We are using the webHttpBinding and have defined some message sizes (optional)
  2. We have specified an endpoint behaviour which use webHttp for communication

Rest all should be self-explanatory I hope.

Now, onto the second part of the post. Consuming the service from JavaScript. Its pretty straightforward actually.

<script
type=&rdquo;text/javascript&rdquo;>
var AllPeople;

function GetNames() {
$.getJSON(&ldquo;http://localhost:15849/RestServ.svc/json/names&rdquo;)
.done(function (data) {

// On success, &lsquo;data&rsquo; contains a list of names.
AllPeople = data;
for (var i = 0; i < AllPeople.length; i++) {
};
});
}

function GetNamesByLastName(lastName) {
$.getJSON(&ldquo;http://localhost:15849/RestServ.svc/json/names?lastname=&rdquo; + lastName)
.done(function (data) {
// On success, &lsquo;data&rsquo; contains a list of names.
AllPeople = data;
for (var i = 0; i < AllPeople.length; i++) {
};
});
}

function SaveNames() {
var names = new Array();
names[0] = &ldquo;Chinmoy&rdquo;;
names[1] = &ldquo;Chandan&rdquo;;
$.ajax({
url: &ldquo;http://localhost:15849/RestServ.svc/json/save&rdquo;,
type: &lsquo;POST&rsquo;,
dataType: &lsquo;json&rsquo;,
data: JSON.stringify(names),
contentType: &ldquo;application/json;charset=utf-8&Prime;,
success: function (data) {
alert(&lsquo;Data Succesfully saved in DB&rsquo;);
},
error: function () {
alert(&lsquo;Data could not be saved in DB. Please Try again.&rsquo;);
}
});
}

</script>

The code above should be self-explanatory. What it is doing is simply making REST calls to our WCF services operations.

And that’s all we need to do to make it work. You can download the project from here.

There are few other things which become a challenge when we implement them in WCF Rest service (like uploading and downloading a file). I’ll be covering this as well as a few gotchas (.net 3.5 specific) in a future post.

Hope the explanation has been simple enough. If you happen to find any issues while implementing the same, shout out in the comments below.

The post Creating and consuming a RESTful service using WCF and JavaScript appeared first on Chinmoy Mohanty's Blog.

License

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

Share

About the Author

Chinmoy Mohanty
Software Developer
India India
I am a Developer working across .NET Technologies.
Passionate about WEB technologies more than anything.
Fascinated about the idea of how the WEB world and the WinForm world are slowly merging into each other, with a very thin line to differentiate them.
 
I am an active blogger and I blog mostly about Technology. You can find my BLOG here.
 
Also, I am active on various techical forums like StackOverflow

Additionally, You can find my Presentations on SlideShare
Follow on   Google+   LinkedIn

Comments and Discussions

 
-- There are no messages in this forum --
| Advertise | Privacy | Mobile
Web02 | 2.8.141015.1 | Last Updated 17 Jul 2014
Article Copyright 2014 by Chinmoy Mohanty
Everything else Copyright © CodeProject, 1999-2014
Terms of Service
Layout: fixed | fluid