Microsoft’s WCF DataContractJsonSerializer sucks!
Anybody who has tried to write a RESTful JSON service in WCF will have hit a wall of hurt as soon as they try to do anything beyond returning a simple string. Enums don’t work how you would want (returning a string instead of the integer value), and error messages are still returned as either XML or (even worse) HTML.
There are some partial solutions online, particularly a great starting point provided by Jeroen Hildering on his blog post, however I found there were still a few further issues I wanted to solve.
In the interests of saving people any future pain, I’ve decided to put my finished code up on GitHub.
It is very simple to implement, firstly you have to add the Newtonsoft.Json library to your project – I’ll leave this as an exercise! After that just drop the file into your WCF project, and add the following lines to your Web.config:
In the system.serviceModel/behaviors/endpointBehaviors/behavior node, add the following below your webHttp node:
<newtonsoftJsonBehavior includeExceptionDetailInFaults="true" />
In the system.serviceModel/bindings/webHttpBinding/binding node, add the following attribute:
Add the following XML inside the system.serviceModel node:
<extensions> <behaviorExtensions> <add name="newtonsoftJsonBehavior" type="JonGrant.Json.NewtonsoftJsonBehaviorExtension, YourAssemblyNameHere" /> </behaviorExtensions> </extensions>
You can also see a sample Web.config file also on GitHub, if that helps.