onsdag den 4. april 2012

REST, JSON and WCF

Representational State Transfer (or REST) has seen a rise in popularity in the last few years. I think this has to do with the webbrowser becomming a platform in its own and the need for an easy to use and read web service has increased. Today you might have mobile apps, clientside applications, websites or even embedded software that needs to gather data from a single service.

SOAP has it's uses but when it comes to humanreadability, ease of implementation and it's lightweightness there is nothing better than REST.

There are hundreds of ways to implement a REST service, im a .NET developer and such will use those tools to build it. You can emulate a lot of the REST behaviour using the MVC framework but i will be creating a real REST service in WCF.NET4.

Start by creating a standard WCF Service in Visual Studio. By default it will be setup to use SOAP. So the first thing we have to do is change it to REST. To do that right-click your .svc file and choose "view markup". At the end of the line (inside the tag) add:

Factory="System.ServiceModel.Activation.WebServiceHostFactory"

It should look somewhat similiar to this:

<%ServiceHost 
    language=c#
    Debug="true"
    Service="Microsoft.Samples.Service"
    Factory=System.ServiceModel.Activation.WebServiceHostFactory%>

You can now add your methods to your service interface. A couple of annotations need to be present for the service to know what you want to do. The following example of a method, takes a JSON string as a parameter and returns JSON as the result.
[OperationContract]
        [WebInvoke(
            BodyStyle = WebMessageBodyStyle.Bare,
            RequestFormat = WebMessageFormat.Json,
            ResponseFormat = WebMessageFormat.Json,
            UriTemplate = "/ReportService?request={json}")]
        void ReportService(String json);

You can go ahead and implement it in your svc class now. Im using JSON.Net for my serializing and deserializing needs when it comes to JSON. You can get it here: http://json.codeplex.com/ or via NuGET, which ever you prefer.
This sample method deserializes the json request, works with the data and serializes objects for the json response.

        public string ForecastService(string json)
        {
            if (String.IsNullOrEmpty(json))
            {
                throw new ArgumentNullException("json", "request cannot be null or empty");
            }

            var request = JsonConvert.DeserializeObject(json, typeof(Model.ForecastServiceRequestObject));
            var response = new ForecastServiceResponseObject();
            
            //Do something with the request

            var jsonResponse = JsonConvert.SerializeObject(response, Formatting.Indented);

            HttpContext.Current.Response.ContentType = "application/json; charset=utf-8";
            HttpContext.Current.Response.Write(jsonResponse);
        }

Lines 15 and 16 use the basic ways to communicate via the HTTP protocol. By writing to the response and setting the ContentType mime we give browsers and applications optimal chance of understanding what we are sending. This is also why our return type is "void". We are not returning anything, were writing a response like any webpage would.

Running the service now will most likely result in an error. Seeing as we are using HttpContext the service will need certain tools from ASP.NET. This is fixed easily. Simply add the following to your web.config

 

  
    
  


Optionally decorate your service with the following annotation to force it through.

[AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Required)]

That's it, you are now ready to deliver data to the world.