Tuesday, May 6, 2008

RESTful Example

Here is an example on how you would create a RESTful webservice with the WCF Web programming model. I assume that you know how to write a WCF service and host it in IIS.
In this example I am going to create a service that will say "Hello" plus a string that is passed into the service, further more the service is going to be hosted in IIS.
the following is a WCF service class,
[ServiceContract]

public interface ITest
{
[OperationContract]
[WebGet(UriTemplate="/SayHello/{str}",ResponseFormat= ebMessageFormat.Xml)]
string SayHello(string str);
}
public class TestImpl : ITest

{
public string SayHello(string str) { return "Hello " + str; }
}

SayHello is our service operation. Note that this is a general WCF service with addittion of a [WebGet] attribute on top of our service operation. by using the [WebGet] attribute we mean that the operation is to be invoked with the HTTP GET verb.The next step is to define our .svc file for our service, the content of the .svc file would look like this.
< @ ServiceHost language=c# Debug="true" Service="RestService.TestImpl" Factory="System.ServiceModel.Activation.WebServiceHostFactory" % >

Again this a general .svc file with the exception of having a WebServiceHostFactory specifed as a factory class to create the appopriate webHttpbinding endpoint.
Now all we have to do is host the service in IIS. The binding used to create RESTfull services, the webHttpbinding does not support multiple authentication, therefor make sure to select only one type of authentication for the directory security in IIS.
We are done...you can access you service like this (assuming that your IIS is running local):
http://localhost/RestService/RstSvc.svc/SayHello/ Iron Man
your response would look something like this...

<string xmlns="http://schemas.microsoft.com/2003/10/Serialization/%22>Hello Iron Man</string >
If you notice carefully, you would see that the way we sent the request is mapped to our [WebGet] attribute's UriTemplate : [WebGet(UriTemplate="/SayHello/{str})]" where {str} is a place holder for the parameter of the operation. You would also see that the response format is set to xml. ResponseFormat= WebMessageFormat.Xml, so the response will be sent to us in xml.


No comments:

Post a Comment