Friday, February 25, 2011

Create a REST WCF Service

Let's create a WCF Service Application project, called DemoRESTService.

using System.ServiceModel;
using System.Runtime.Serialization;

namespace DemoRESTService
{
[DataContract]
public class Product
{
[DataMember]
public int ID { get; set; }

[DataMember]
public string Name { get; set; }

[DataMember]
public double Price { get; set; }

}

[ServiceContract]
public interface IGetProductService
{
[OperationContract]
Product GetProduct(int id, string name, double price);
}

public Product GetProduct(int id, string name, double price)
{
return new Product() { ID = id, Name = name, Price = price };
}
}

Compile, this is our namal WCF service. We can use Service Client tool to test:



These is our old knowledge, so we are not go too much into details. To create a REST WCF service, the most important thing is the WebGet attribute. In the WebGet Attribute we can set the UriTemplate, if we don't set this value, the REST service will have the Url like: http://.... svc/GetProduct?id=5&name=Apple&price=1.25 to call the REST service. Here we use the default uri template. We can also specify the Service Response data format as Json or XML in WebGet attribute. In my next series of blog, I am going to write something on javaScript/Jquery cross domain call, JsonP et al, so I get the respose format to be Json. The WebGet attribute is like [WebGet(ResponseFormat = WebMessageFormat.Json)] for my furture use.

The hard thing is web.config. We can use WCF Service Configuration Editor to edit the web.config file. But it is still need careful writing for this part.



I create the web.config file as picture below (we can use this as template for furture use).


Let's compile and now we create a REST WCF service below.


About the hosting,(Address, Binding, Contract), there are too much materials on this, I am not going to talk in my blog.

Let's in IE, we type the address:

http://..../GetProductService.svc/GetProduct?id=1&name=apple&price=1.25

We will get a Json results return back. (notice for url querystring the querystring's parameters should also be able to be seperated by semicolumn ";", http://..../GetProductService.svc/GetProduct?id=1;name=apple;price=1.25 should also work, but it doesn't. This is a Microsoft bug).

We can see the result is Json format:


There should aslo have materials to talk about how to build a REST Web Service has Json Response format. If anyone is interested in that, he can search the related materials. You can download my Demo Code Here.

No comments: