Creating a REST JSON WCF Service with C# .NET.

“Boring conversation anyway.” – Han Solo.

Ok, I think this post possibly has too many acronyms in the title. This post is about creating a WCF service that can be consumed by a client using the REST (representational state transfer) architectural style, and using JSON (JavaScript Object Notation) for data transfer. Why would we do this? Partly, and I can’t stress this one enough, it’s actually loads of fun… Additionally, with XML no longer being flavour of the month, JSON has become much more popular for transferring data in this situation.

I needed to determine how to do this recently to enable an existing application system on Linux that uses REST/JSON to access a WCF service without asking them to convert to SOAP/XML.

I’ve created a couple of posts already describing how to use WCF in C#/.NET. I’ll be using similar code, but modifying it for JSON as opposed to the default SOAP/XML.

It’s actually quite a simple change. The change is pretty much just made in the interface description itself. I’ve also included a more complex response data type.

Here’s the response data type.

using System;
using System.Collections.Generic;
using System.Linq;
using System.ServiceModel;
using System.Text;
using System.Threading.Tasks;

namespace SampleWindowsService
{
    public class RESTResponse
    {
        public string strResponseCode;
        public string strResponseText;
    }
}

Here’s the “before” interface.
The WCF calls for this service would have used SOAP/XML.

using System;
using System.Collections.Generic;
using System.Linq;
using System.ServiceModel;
using System.Text;
using System.Threading.Tasks;

namespace SampleWindowsService
{
    [ServiceContract]
    public interface IIPCService
    {
        [OperationContract]
        RESTResponse Function1(string strArgument1, string strArgument2);
    }
}

Here’s the “after” interface.
You’ll need to add a reference to System.ServiceModel.Web.Dll as well for this.

using System;
using System.Collections.Generic;
using System.Linq;
using System.ServiceModel;
using System.ServiceModel.Web;
using System.Text;
using System.Threading.Tasks;

namespace SampleWindowsService
{
    [ServiceContract(SessionMode = SessionMode.NotAllowed)]
    public interface IIPCService
    {
        [WebInvoke(Method = "POST",
            BodyStyle = WebMessageBodyStyle.WrappedRequest,
            RequestFormat = WebMessageFormat.Json,
            ResponseFormat = WebMessageFormat.Json,
            UriTemplate = "Function1")]
        [OperationContract]
        RESTResponse Function1(string strArgument1, string strArgument2);
    }
}

Super cool. Simply changing the attributes for the functions in the interface will allow it to send/receive JSON data instead. As an example, this is what the HTTP flow would look like between the client and the server.

POST /BaseApplicationURI/Function1 HTTP/1.1
Content-Type: application/json; charset=utf-8
Host: server:port
Content-Length: 48
Connection: Keep-Alive

{"strArgument1":"test1","strArgument2:"test2"}

HTTP/1.1 200 OK
Content-Length: 78
Content-Type: application/json; charset=utf-8
Server: Microsoft-HTTPAPI/2.0
Date: Fri, 20 Jun 2014 05:28:56 GMT

{"strResponseCode":"0","strResponseDescription":"That worked apparently."}

Looking at the code, the first thing to mention there is that I’ve disabled session state configuration for the service – REST services should be stateless.

As for the rest of the code, the changes were in the WebInvoke attribute.

  • Method = “POST” – whatever you prefer, although there are some conventions used regarding which method to apply. For example you may use the GET method for returning data, and the PUT method for changing data.
  • BodyStyle = WebMessageBodyStyle.WrappedRequest – as we have multiple request variables, this adds an overall set of brackets around the request data (the outer { and } in the HTTP flow above).
  • RequestFormat = WebMessageFormat.Json – Expect the input parameters to be in JSON encoding.
  • ResponseFormat = WebMessageFormat.Json –  Send the response data in JSON encoding.
  • UriTemplate = “Function1” – this is where we specify the portion of the URI that should be associated with this function. Typically, when using SOAP/XML, the function name is contained within the SOAP message. Without SOAP/XML, we need to use the URI to specify the function we’re calling. You can actually embed parameters in the URI string as well (Function1/{strParameter1}).

The last part of the code to be changed is where we start the service itself. The primary change below from my previous WCF examples is that I’m now using the WebHttpBinding instead of BasicHttpBinding.

public static void StartService()
{
    WebHttpBinding webBinding = new WebHttpBinding(); 

    sHost = new ServiceHost(typeof(IPCService));

    sHost.AddServiceEndpoint(typeof(IIPCService), webBinding, "http://server:port/BaseApplicationURI").EndpointBehaviors.Add(new WebHttpBehavior());

    sHost.Open();
}

All of this is infinitely configurable, but hopefully this will help you get the hang of the basics. Being able to use JSON for a WCF service is very handy when you’re dealing with a multiple operating system environment.

Enjoy.

~ Mike

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s