Monday, May 2, 2011

RESTful Services With WCF in Asp.Net

What is REST
REST stands for Representational State Transfer. (It is sometimes spelled "ReST".) It relies on a stateless, client-server, cacheable communications protocol -- and in virtually all cases, the HTTP protocol is used.
REST is an architecture style for designing networked applications. The idea is that, rather than using complex mechanisms such as CORBA, RPC or SOAP to connect between machines, simple HTTP is used to make calls between machines.
  • In many ways, the World Wide Web itself, based on HTTP, can be viewed as a REST-based architecture.
RESTful applications use HTTP requests to post data (create and/or update), read data (e.g., make queries), and delete data. Thus, REST uses HTTP for all four CRUD (Create/Read/Update/Delete) operations.
Sample REST Application using WCF
WCF is the Microsoft framework for building applications that communicate over network using different protocols. WCF allows the developers to build distributed applications using SOAP. WCF also had the ability to expose and consume REST services.This post explains how to build REST service using WCF.
Create a new WCF Service in VS 2010 as follows,here select Web Location as Http.

Add the RestService.Svc  file to the solution Explorer .
When you add RestService.svc it will automatically adds IRestService.cs and RestService.cs files to your Solution Explorer

Add following methods in IRestService.cs File

public interface IRestService
   string HelloWorld();
    string HelloWorldWithParameter(string input);

Add folowing NameSpaces and methods to the RestService Class

using System.ServiceModel.Web;
using System.ServiceModel.Activation;
public class RestService
    [WebGet(UriTemplate = "/Hello", ResponseFormat = WebMessageFormat.Xml)]
    string HelloWorld()
        return "Welcome to My First Rest Service";
    [WebGet(UriTemplate = "/Hello/{input}", ResponseFormat = WebMessageFormat.Xml)]
    string HelloWorldWithParameter(string input)
        return input;

Here we can add WebFGet and WebInvoke attributes to the Methods and we can add WebMessage format as Json or Xml

The WebGet attribute exposes operations using the GET verb. The GET has significant advantages over other HTTP verbs. First, the endpoint is directly accessible via a Web browser by typing the URI to the service into the address bar. Parameters can be sent within the URI either as query string parameters or embedded in the URI. Second, clients and other downstream systems such as proxy servers can easily cache resources based on the cache policy for the service. Because of the caching capability, the WebGet attribute should be used only for retrieval.
The WebInvoke attribute exposes services using other HTTP verbs such as POST, PUT, and DELETE. The default is to use POST, but it can be changed by setting the Method property of the attribute. These operations are meant to modify resources; therefore, the WebInvoke attribute is used to make modifications to resources.

 Add the service host declaration with the following attributes

End Point Configuration in Web.config file
      <service name="MyFirstRestWCFService.RestService" behaviorConfiguration="HttpGetMetadata">
        <endpoint address=""
                  contract="MyFirstRestWCFService.IRestService" ></endpoint>
        <endpoint address="mex" binding="mexHttpBinding" contract="IMetadataExchange"></endpoint>
        <behavior name="HttpGetMetadata">
          <serviceMetadata httpGetEnabled="true" />
    <serviceHostingEnvironment multipleSiteBindingsEnabled="true" />

Now Enter this URL in your browser the output will display in XML format,because we have used WebMessage Format as Xml.
How to Consume REST-WCFServices
You can take advantage of the System.Net classes to programmatically issue HTTP requests and process the responses. The following code illustrates how easy this can be by using the HttpWebRequest and HttpWebResponse classes:
string uri = "http://localhost/MyFirstRestWCFService/RestService.svc/Hello";
            HttpWebRequest req = WebRequest.Create(uri) as HttpWebRequest;
            HttpWebResponse resp = req.GetResponse() as HttpWebResponse;
            Stream stream = resp.GetResponseStream();
            StreamReader reader = new StreamReader( stream );
            string text = reader.ReadToEnd();


Now We have learned how to Develop and consume REST Services using WCF.


  1. Thanks a lot for this.It has too help full to me to start wcf concepts.Can you give me more post regarding this?

  2. By Combining the Domain expertise with Low Cost Offshore .NET Development process, CATT Ltd’s Offshore development Model delivers Enhanced Productivity with Quality and Cost Savings. CATT Ltd offers its customers an option of having a Dedicated offshore .NET Developers to augment their IT capabilities by proving access to their Talented professionals and the state-of-the-art infrastructure.

  3. reader.ReadToEnd() will not result "Welcome to My First Rest Service", but gives
    "Welcome to My First Rest Service".
    Please give some solution to retrieve only required text.

  4. Thanks,
    pls give me one simple example How to insert,update,delete,get WCFREST service example,AND also how to consume that service in webpage Pls Help me....

  5. I am developing One WcfRest service
    How can i consume this service in to my ASP.NET webpages,
    plz help me

  6. Can you help me I am creating One Wcfrest service ,
    How To consume this service in my ASP.NET webpages

    My task is I am creating WCFREST service perform all CRUD operations in Database table,Its working With Browser

    Now I am consuming this service my ASP.NET webpages ,

    tell me How can i consume this service in ASP.NET webpages
    plz help me?

    you can understand my English,
    Give me One simple example Creating WCFREST service And perform ALL CRUD operations on DATABASE TABLE?
    How to consume this service in ASP.NET webpages?

    plz help me

    Thank you ,

  7. Nice article..

    But I have found another simple example to call a WCF RestFul Service using jQuery AJAX Call, please refer to link below:-


  8. Really Nice Information,Thank You Very Much For Sharing.
    Web Development Company

  9. I am expecting more interesting topics from you. And this was nice content and definitely it will be useful for many people.

    Back to Original Services Private Limited