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

[ServiceContract]
public interface IRestService
{
    [OperationContract]
   string HelloWorld();
    [OperationContract]
    string HelloWorldWithParameter(string input);
}

Add folowing NameSpaces and methods to the RestService Class

using System.ServiceModel.Web;
using System.ServiceModel.Activation;
[ServiceContract]
public class RestService
{
    [OperationContract]
    [WebGet(UriTemplate = "/Hello", ResponseFormat = WebMessageFormat.Xml)]
    string HelloWorld()
    {
        return "Welcome to My First Rest Service";
    }
   
    [OperationContract]
    [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

WebGet
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.
WebInvoke
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
<system.serviceModel>
    <services>
      <service name="MyFirstRestWCFService.RestService" behaviorConfiguration="HttpGetMetadata">
        <endpoint address=""
                  binding="basicHttpBinding"
                  contract="MyFirstRestWCFService.IRestService" ></endpoint>
        <endpoint address="mex" binding="mexHttpBinding" contract="IMetadataExchange"></endpoint>
      </service>
    </services>
    <behaviors>
      <serviceBehaviors>
        <behavior name="HttpGetMetadata">
          <serviceMetadata httpGetEnabled="true" />
        </behavior>
      </serviceBehaviors>
    </behaviors>
    <serviceHostingEnvironment multipleSiteBindingsEnabled="true" />
  </system.serviceModel>


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();

Conclusion

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

8 comments:

  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?

    ReplyDelete
  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.

    ReplyDelete
  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.

    ReplyDelete
  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 ASP.net webpage Pls Help me....

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

    ReplyDelete
  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 ,
    Anil

    ReplyDelete
  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:-
    http://www.etechpulse.com/2014/03/consume-restful-wcf-service-in-aspnet.html
    http://www.etechpulse.com/2014/03/how-to-consume-wcf-restful-service-in.html

    Thanks

    ReplyDelete
  8. This comment has been removed by the author.

    ReplyDelete