Saturday, February 11, 2012

C# with REST

Steps

1.   We start this example by creating a WCF Service Library project from Visual Studio 2008: 

Provide name, location and solution Name.
name :                   WcfRestService
location :                C:/Project
Solution Name :    WcfRestService 

2.  Next we need to add a reference to the System.ServiceModel.Web framework.  Right click on your project file and select Add Reference…



As this framework is not part of the .Net Framework 4 Client Profile, Visual Studio kindly informs us that it will update our target Framework to the full version of .Net Framework 4.  Click Yes to accept this change:



We are now ready to update our code.
Copy and paste the following code into the App.Config file:


<?xml version="1.0"?>
<configuration>
  <system.serviceModel>
 <services>
   <service name="WcfRestService.Service1">
  <endpoint address="http://localhost/service1" 
      binding="webHttpBinding" 
      contract="WcfRestService.IService1"/>
   </service>
 </services>
 <behaviors>
   <endpointBehaviors>
  <behavior>
    <webHttp />
  </behavior>
   </endpointBehaviors>
 </behaviors>
  </system.serviceModel>
  <startup>
 <supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.0"/>
  </startup>
</configuration>
 
 
Notice the binding is set to webHttpBinding as opposed to the normal project template default of wsHttpBinding. 
The other important change is the addition of an endpointBehavior for WebHttp.
These two changes are required to enable XML over REST for WCF.

Create  method in IService.cs

[ServiceContract]

using System.ServiceModel;

namespace WcfRestService
{
    [ServiceContract]
    public interface IService
    {
       [OperationContract]
       TestElement HitURL(string id);
    } 
}
 
Create or Modify the Service1 Class. 
 
using System;
using System.ServiceModel.Web;

namespace WcfRestService
{
    public class Service1 : IService1
    {
        [WebInvoke(Method = "GET", 
                    ResponseFormat = WebMessageFormat.Xml, 
                    UriTemplate = "hit/{id}")]
        public TestElement HitURL(string id)
        {

            return new TestElement()
              {
                 Id = Convert.ToInt32(id), 
                 Name = "Converted"
              };
        }
    }

    public class TestElement 
    {
        public int Id { get; set; }
        public string Name { get; set; }
    }
}
 
 
The key elements here are the attributes applied to the method.  We are enabling the method to be called over HTTP GET, returning the data in Xml format and setting the Uri template to ensure we are using a RESTful interface.
To test your brand new service we will pass in the id value of 30 simply by opening your favourite browser and pasting in the following URL:

http://localhost/Service1/hit/30

 
 
 
 

No comments :

Post a Comment