This post shows how to implement a RESTful service using .NET framework 4.0.

Using the REST terminology, we will call "resource" any object, identified in an unique way by an URI, on which to invoke one of the "request methods" ADD, PUT, DELETE, GET.

In our example the resource is represented by the "Contact" object defined as follow:

public class Contact
{
     public int ContactId { get; set; }
     public string fName { get; set; }
     public string lName { get; set; }
     public string eMail { get; set; }
}

Implement a RESTful service in .NET 4.0 is simple as to write a wcf service. Infact .Net 4.0 provides a very simple REST programming model thanks to the WebInvoke/WebGet attributes.
Is sufficient decorate the service operation with one of these attributes and it can be called by the WCF REST programming model.

The WebInvoke attribute exposes some properties through which you can specify the REST options:

Method: Gets and sets the protocol (for example HTTP) method the service operation responds to (ADD, PUT, DELETE, GET)

RequestFormat: determines the format of requests made to a service operation. The possible values are Xml and Json.

ResponseFormat: determines the format of responses sent from a service operation. The possible values are Xml and Json.

UriTemplate: determines which requests get dispatched to which service operations.

You can also use the WebInvoke attribute insted of the WebGet attribute specifying Method = "GET".

Here an example of service contract:

[ServiceContract]
public interface IContacts
{
    [OperationContract]
    [WebInvoke(Method = "ADD",
         ResponseFormat = WebMessageFormat.Json,
         RequestFormat = WebMessageFormat.Json, UriTemplate = "Add")]
    Contact Add(Contact contact);

    [OperationContract]
    [WebInvoke(Method = "DELETE",
        ResponseFormat = WebMessageFormat.Json, UriTemplate = "Delete")]
    void Delete(string id);

    [OperationContract]
    [WebInvoke(Method = "PUT",
        ResponseFormat = WebMessageFormat.Json)]
    void Update(Contact contact);

    [OperationContract]
    [WebInvoke(Method = "GET",
        ResponseFormat = WebMessageFormat.Json)]
     List<Contact> GetAll();

    [OperationContract]
    [WebInvoke(Method = "GET",
        ResponseFormat = WebMessageFormat.Json, UriTemplate = "GetContact/{id}")]
    Contact GetContact(string id);
}

In a typical scenario, the service contract IContacts could be implemented by the Contacts.svc service, hosted at the address http://myserver/contactservice/Contacts.svc.

In this scanario the service operations can be invoked in the following way:

http://myserver/contactservice/Contacts.svc/Add
http://myserver/contactservice/Contacts.svc/Update
http://myserver/contactservice/Contacts.svc/GetContact/123
http://myserver/contactservice/Contacts.svc/Delete
http://myserver/contactservice/Contacts.svc/GetAll