Articles Creating and Consuming a RESTful Service using WCF and JavaScript by Chinmoy Mohanty

emailx45

Местный
Регистрация
5 Май 2008
Сообщения
3,571
Реакции
2,439
Credits
574
Creating and Consuming a RESTful Service using WCF and JavaScript
Chinmoy Mohanty - 01/Aug/2020
[SHOWTOGROUPS=4,20,22]

How to create and consume a RESTful service using WCF and JavaScript
In this post, you will see how to make a WCF service RESTful and how to consume the service from JavaScript

REST !! REST !! REST !!
It’s the buzz word recently with the advent of mobile revolution. You know what’s worse than not having heard about a buzz word!! It's having heard about it, but having no idea about 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 it wasn’t possible to use ASP.NET WebApi. And I’m glad that I did.

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 it's 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 is happening because we have no idea of 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 things 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 the operation will 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 are 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>() { "Ram Kumar", "Shyam Kumar", "Laxman Prasad", "Ram Prasad" };
return lst;
}

public List<string> GetNamesByLastName(string lastname)
{
List<string> lst = new
List<string>() { "Ram Kumar", "Shyam Kumar", "Laxman Prasad", "Ram Prasad" };
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.
Hide   Shrink [IMG]https://www.codeproject.com/images/arrow-up-16.png[/IMG] Copy Code
<system.serviceModel>
<bindings>
<webHttpBinding>
<binding

name="MyWcfRestService.WebHttp"

maxBufferSize="2147483647"

maxBufferPoolSize="2147483647"

maxReceivedMessageSize="2147483647"

transferMode="Streamed"

sendTimeout="00:05:00">
<readerQuotas

maxDepth="2147483647"

maxStringContentLength="2147483647"

maxArrayLength="2147483647"

maxBytesPerRead="2147483647"

maxNameTableCharCount="2147483647"/>
<security

mode="None" />
</binding>
</webHttpBinding>
</bindings>
<services>
<service

behaviorConfiguration="MyWcfRestService.RestServBehavior"

name="MyWcfRestService.RestServ">
<endpoint

address=""

behaviorConfiguration="web"

binding="webHttpBinding"

bindingConfiguration="MyWcfRestService.WebHttp"

contract="MyWcfRestService.IRestServ">
<identity>
<dns

value="localhost" />
</identity>
</endpoint>
<endpoint

address="mex"

binding="mexHttpBinding"

contract="IMetadataExchange" />
</service>
</services>
<behaviors>
<endpointBehaviors>
<behavior

name="web">
<webHttp />
</behavior>
</endpointBehaviors>
<serviceBehaviors>
<behavior

name="MyWcfRestService.RestServBehavior">
<serviceMetadata

httpGetEnabled="true" />
<serviceDebug

includeExceptionDetailInFaults="true" />
</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
Everything else should be self-explanatory, I hope.
Now, onto the second part of the post. Consuming the service from JavaScript. It's pretty straightforward actually.
Код:
<script
type="text/javascript">
var AllPeople;

function GetNames() {
$.getJSON("http://localhost:15849/RestServ.svc/json/names")
.done(function (data) {

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

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

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

</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 Для просмотра ссылки Войди или Зарегистрируйся.

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.


[/SHOWTOGROUPS]