Consuming WCF RIA Services Domain Services as JSON

I was working on a Silverlight application with a WCF RIA Services middle-tier recently when the need arose for us to add an HTML/Javascript front-end in addition to the existing Silverlight one. I knew Microsoft offerd WebAPI services that are specially geared toward being consumed by Javascript clients, but the team wanted to leverage the existing work we'd done on the middle-tier in RIA Services if possible.

So the question was, could I publish my existing RIA domain service in a way that is Javascript-friendly? WCF RIA Services exposes its domain services in a binary-format by default. Javascript works better with a text-format, especially JSON. With the right configuration, it is possible to expose you RIA domain service as JSON. Here's how to do it:
  1. Make sure you are using the latest version of RIA Services and the RIA Services Toolkit (currently v1.0 SP2 and September 2011, respectively). If not, download them and install them now.
  2. From your web project, add a reference to "Microsoft.ServiceModel.DomainServices.Hosting" which installs with the Toolkit. Notice that you will already have a reference to "System.ServiceModel.DomainServices.Hosting" which is a different assembly in spite of the very similar names.
  3. Configure your web.config file to allow for the <domainServices> node, if it hasn't been already:
    <configuration>
      <configSections>
        <sectionGroup name="system.serviceModel">
          <section name="domainServices" type="System.ServiceModel.DomainServices.Hosting.DomainServicesSection, System.ServiceModel.DomainServices.Hosting, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" allowDefinition="MachineToApplication" requirePermission="false" />
        </sectionGroup>
      </configSections>
      ...
  4. Add the JSON end-point under system.serviceModel:
    <system.serviceModel>
      <domainServices>
        <endpoints>
          <add name="Json" type="Microsoft.ServiceModel.DomainServices.Hosting.JsonEndpointFactory, Microsoft.ServiceModel.DomainServices.Hosting, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" />
        </endpoints>
      </domainServices>
  5. Now simply configure your Javascript code to access your new JSON service using the following URL format (where the dots from the namespace are replaced with dashes):
    /NameSpace-Path-To-Service-DomainServiceClass.svc/json/MethodName

    for example:
    /SLRiaWithJson-Web-Services-SampleDatabaseService.svc/json/GetWidgets
You can now consume your RIA domain service as JSON in Javascript. I created a sample application which you can download to see it in action.

comments powered by Disqus