Develop and Consume WCF REST Service

This article shows a simple way of developing WCF REST Services and consuming them through JQuery in ASP.Net application.

What is REST?

REST – Representational State Transfer in an architectural style for designing network applications. The main idea behind is that rather using different mechanisms such as SOAP, CORBA, RPC to connect between systems, user can use simple HTTP to make calls between them. RESTful Services use HTTP requests to POST (modify or update) data, to DEL (delete) data or GET(retrieve) data.

What is JQuery?

jQuery is a coding language that is a branch from JavaScript. jQuery works like JavaScript where it’s used to help with interaction and effects with your development code.

You can find the complete tutorial of JQuery at http://docs.jquery.com/Tutorials:How_jQuery_Works

Let’s start the real Coding work.

Creating WCF Rest Service

  1. Open Visual Studio
  2. Create a WCF Service Application Project.
  3. Create a new Service Interface named as IRestServiceImpl.cs, following code snippet shows the complete code of this interface.

     

    namespace RestService

    {


    // NOTE: You can use the “Rename” command on the “Refactor” menu to change the interface name “IRestServiceImpl” in both code and config file together.

    [ServiceContract]


    public
    interface
    IRestServiceImpl

    {

    [OperationContract]

    [WebGet(ResponseFormat=WebMessageFormat.Xml, BodyStyle=WebMessageBodyStyle.Wrapped, UriTemplate= “xml/{id}”)]


    string XMLData(string id);

     

    [OperationContract]

    [WebGet(ResponseFormat=WebMessageFormat.Json, BodyStyle=WebMessageBodyStyle.Wrapped, UriTemplate=“json/{id}”)]


    string JSONData(string id);

    }

    }

     

    In WCF all the web methods should be annotated with the OperationContract and the service class should be annotated with the ServiceContract. This is necessary for both SOAP based or REST based calls.

    Rest, as per the above code there are two WCF operation contracts; one returns data in XML and the other returns data in JSON. JSON data is more less in size as it does not contains tags and all that what xml have. Both the methods are annotated with WebGet attribute.
    In WCF for making REST based calls you need to annotate the method either using WebGet or WebInvoke to define specific mapping to the HTTP uniform interface. The reason Microsoft provided two attributes because GET requests are logically different from POST, DELETE, PUT etc. the bottom line is if you want to use HTTP GET you use WebGet otherwise WebInvoke for all others. Here as we are retrieving the data I have used WebGet.

     

    ResponseFormat tell what the format of the data that is travel back to client. There are two formats XML or JSON. UriTemplate helps to specify the template of REST calls over HTTP and the way method will be accessible from client in a REST way.

     

  4. Create a RestServiceImpl.cs class and implement IRestServiceImpl.cs interface. Following code shows the complete snippet of RestServiceImpl.cs

     

    namespace RestService

    {


    // NOTE: You can use the “Rename” command on the “Refactor” menu to change the class name “RestServiceImpl” in code, svc and config file together.


    public
    class
    RestServiceImpl : IRestServiceImpl

    {

     


    public
    string XMLData(string id)

    {


    return
    “you have typed=” + id;

    }

 


public
string JSONData(string id)

{


return
“you have typed=” + id;

}

}

}

 

Testing WCF Service

  1. Now just run the WCF Service Application and test. Below URL shows the way of making REST calls.

    For XML,

    http://localhost:31189/RestServiceImpl.svc/xml/123

    For JSON,

    http://localhost:31189/RestServiceImpl.svc/json/123

Creating ASP.Net Web Application

 

  1. Create ASP.Net web project to consume WCF REST service
  2. Open default.aspx page and add html text box and button

     

<input
id=”text” type=”text”/>

<input
id=”set” type=”button” value=”Click” onclick=”RetrieveVIAWCFREST();”/>

 

  1. Now define the function RetrieveVIAWCFREST under script tag

     

    <script>

     


    function RetrieveVIAWCFREST() {

     

    var textVal= $(‘#text’).val();

     

    $.ajax({

    type: “GET”,

    contentType: “application/json; charset=utf-8”,

    url: http://localhost:31189/RestServiceImpl.svc/json/&#8221;+textVal,

    dataType: “json”,

    processdata: false,

    success: function (data) {


    var result=data.JSONDataResult;

    alert(result);

    },

    error: function () { alert(“Not Done”); }

    });

     

    }

     


    </script>

     

.ajax is a JQuery function which helps the developer to transport the data from client server in a simple way. It calls XMLHttpRequest object inside and make calls automatically. But developer has to define certain attribute values to make call smoothly.

When the call executes successfully success function will be called and the appropriate action will be executed inside it. On error, error function will be called and the appropriate action will be executed. There is a complete attribute also and user can define a function on complete event. Please check JQuery docs for more information.

 

Running Web Application

Let’s run the Web application. Enter text in the textbox and click the ‘Click’ button.

 

Advertisements

94 thoughts on “Develop and Consume WCF REST Service

  1. Thank you for some other informative website. Where else may just I am getting that kind of info written in such an ideal way? I’ve a undertaking that I am just now operating on, and I have been at the glance out for such info.

  2. Its like you learn my thoughts! You appear to grasp a lot approximately this, such as you wrote the ebook in it or something. I feel that you simply can do with some percent to power the message home a little bit, but instead of that, this is fantastic blog. A fantastic read. I will definitely be back.

  3. you are truly a good webmaster. The website loading speed is amazing. It sort of feels that you are doing any unique trick. Moreover, The contents are masterwork. you’ve performed a fantastic activity on this matter!

  4. I became honored to get a call from my friend immediately he discovered the important recommendations shared in your site. Examining your blog article is a real great experience. Many thanks for thinking about readers just like me, and I wish you the best of achievements as a professional in this arena.

  5. I really like your writing style, good info, thank you for posting :D. “If a cluttered desk is the sign of a cluttered mind, what is the significance of a clean desk” by Laurence J. Peter.

  6. I believe this internet site has some real great info for everyone. “The fewer the words, the better the prayer.” by Martin Luther.

  7. Hey there exceptional website! Does running a blog similar to this require a large amount of work? I have no expertise in programming however I was hoping to start my own blog in the near future. Anyway, if you have any recommendations or techniques for new blog owners please share. I understand this is off subject nevertheless I simply needed to ask. Kudos!

  8. You really make it appear really easy with your presentation however I in finding this topic to be actually one thing which I think I might never understand. It sort of feels too complicated and extremely extensive for me. I am having a look ahead for your next post, I will attempt to get the dangle of it!

  9. Hi there! This post could not be written any better! Reading through this post reminds me of my good old room mate! He always kept talking about this. I will forward this article to him. Fairly certain he will have a good read. Many thanks for sharing!

  10. A person essentially assist to make critically articles I’d state. That is the very first time I frequented your web page and thus far? I surprised with the research you made to create this actual submit incredible. Magnificent process!

  11. We wish to thank you once again for the wonderful ideas you offered Jeremy when preparing a post-graduate research in addition to, most importantly, regarding providing each of the ideas in a blog post. If we had been aware of your site a year ago, we might have been saved the nonessential measures we were implementing. Thanks to you.

  12. I would like to thank you for the efforts you have put in writing this web site. I am hoping the same high-grade web site post from you in the upcoming also. Actually your creative writing skills has encouraged me to get my own website now. Actually the blogging is spreading its wings fast. Your write up is a good example of it.

  13. This is very interesting, You are a very professional blogger. I have joined your feed and look ahead to seeking extra of your magnificent post. Additionally, I have shared your site in my social networks!

  14. Merely to follow up on the up-date of this issue on your website and would really want to let you know just how much I liked the time you took to generate this helpful post. In the post, you spoke regarding how to really handle this matter with all comfort. It would be my own pleasure to build up some more strategies from your site and come as much as offer other individuals what I learned from you. I appreciate your usual good effort.

  15. My spouse and I stumbled over here coming from a different web page and thought I may as well check things out. I like what I see so i am just following you. Look forward to looking over your web page repeatedly.

  16. I really enjoy reading through on this internet site , it holds great content . “We find comfort among those who agree with us–growth among those who don’t.” by Frank A. Clark.

  17. We would like to thank you once again for the gorgeous ideas you gave Jeremy when preparing her post-graduate research and, most importantly, pertaining to providing all of the ideas in one blog post. If we had known of your web page a year ago, we would have been saved the pointless measures we were implementing. Thank you very much.

  18. I’m not sure where you are getting your information, but good topic. I needs to spend some time learning more or understanding more. Thanks for wonderful info I was looking for this info for my mission.

  19. We wish to thank you again for the stunning ideas you gave Jeremy when preparing a post-graduate research in addition to, most importantly, pertaining to providing all of the ideas within a blog post. If we had known of your website a year ago, i’d have been rescued from the unwanted measures we were employing. Thanks to you.

  20. A person essentially help to make critically posts I would state. That is the very first time I frequented your web page and up to now? I amazed with the research you made to make this particular publish amazing. Magnificent activity!

  21. I simply could not leave your web site before suggesting that I extremely loved the standard information a person supply for your guests? Is going to be back steadily in order to check out new posts.

  22. My spouse and i still can’t quite think that I could always be one of those studying the important ideas found on your web site. My family and I are sincerely thankful for the generosity and for giving me the advantage pursue the chosen profession path. Thank you for the important information I got from your web-site.

  23. Hey! awesome blog! I happen to be a daily visitor to your site (somewhat more like addict 😛 ) of this website. Just wanted to say I appreciate your blogs and am looking forward for more to come!

  24. I appreciate an unbelievable publish, may examine your others posts. many thanks for your thinking within this, I felt a lttle bit made an impact to by this article. Many thanks again! You earn a terrific moment. Portrays natures best by the wonderful report here. I do think that if a greater number of people consideration for it like this, they’d have got a better time period receive the suspend ofing the matter.

  25. I believe other website proprietors should take this site as an model, very clean and fantastic user friendly style . “He who lives without folly isn’t so wise as he thinks.” by Francois de La Rochefoucauld.

  26. Thank you for the blog post. Jones and I are already saving for our new guide on this issue and your blog post has made us to save money. Your thinking really answered all our inquiries. In fact, in excess of what we had acknowledged prior to when we stumbled on your fantastic blog. I actually no longer have doubts and a troubled mind because you completely attended to the needs in this article. Thanks

  27. Hey There. I discovered your weblog working with msn. This can be a very neatly written write-up. I will make sure to bookmark it and come back to learn added of one’s valuable information. Thank you for the post. I will undoubtedly return.

  28. I do agree with all the ideas you have presented in your post. They’re very convincing and will definitely work. Still, the posts are too short for beginners. Could you please extend them a little from next time? Thanks for the post.

  29. I merely wanted to thank you yet again for your amazing website you have built here. It’s full of ideas for those who are definitely interested in this particular subject, particularly this very post. You’re really all amazingly sweet and also thoughtful of others as well as reading your site posts is a great delight to me. And thats a generous present! Jeff and I really have enjoyment making use of your tips in what we should do in a few days. Our checklist is a mile long and tips will definitely be put to great use.

  30. Youre so cool! I dont suppose Ive read anything like this before. So good to find someone with some unique ideas on this subject. realy thank you for starting this up. this web site is one thing that is wanted on the web, somebody with just a little originality. helpful job for bringing one thing new to the web!

  31. I wanted to follow up and allow you to know how great I cherished discovering your blog today. I would consider it a honor to operate at my business office and be able to use the tips discussed on your website and also participate in visitors’ opinions like this. Should a position regarding guest writer become offered at your end, please let me know.

  32. Aw, this was an extremely nice post. Spending some time and actual effort to create a top notch article… but what can I say… I hesitate a lot and never seem to get nearly anything done.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s