Monday, 25 March 2013

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.

No comments:

Post a Comment