My Big Ol’ JSON Rest mistake

This was really kicking my bahonkus. I’ve created a JSON RESTful service using WCF and my “get” calls were working like a clock.  But, every time I made a “post” request I got the same error: “Encountered unexpected character ‘x’”.  I spent a day and a half trying to fix it by changing my behaviors and modifying the WebEnvoke attribute…  Then I stumbled across this blog post:
http://encosia.com/3-mistakes-to-avoid-when-using-jquery-with-aspnet-ajax/

And all my problems were caused by the third mistake he lists: JQuery will URL-encode the data. As it turns out, the xml parser that handles these requests does not care for the encoding, and will throw a super cryptic error. And searching for JSON REST WCF errors will give you a lot of results, but none that answer this question. Ah abstraction, you fickle mistress…

Advertisements

Creating a RESTful JSON service in WCF…

…is harder then I thought.  I finally got it working but I had to merge the “How To” advice from two different sources:

http://www.codeproject.com/Articles/167159/How-to-create-a-JSON-WCF-RESTful-Service-in-60-sec?msg=4102667#xx4102667xx

http://christopherdeweese.com/blog2/post/drop-the-soap-wcf-rest-and-pretty-uris-in-net-4

 

My actual steps were:

  1. Create a new service from the online template:

    Restful service

    This got me pretty far, and I was able to deploy my service to my local IIS, but the result always returned XML.  Even when I specified JSON as the return type. So…

  2. To get the result to return JSON you need to:

    Restful_service_web_config

After these 2 changes (and some tweaking to the global.asax file to modify routes) my service was off to the races!