There are questions similar to this, but they involved returning objects which are automatically parsed to JSON.
I have a string that consists of JSON formatted data that I simply want to return from my WCF web service so that I can read it in ajax.
It doesn’t work by simply returning the string (I get a parser error from the ajax). I was wondering if there was a specific way that I should be returning my JSON string from the web service?
My ajax is fine, because I’ve tested it with other external json providing web services, but it doesn’t work with my own (so I’m assuming it’s the data I’m returning).
For reference, here’s the important part of the getting and returning of the JSON:
WebResponse wr = myReq.GetResponse();
Stream receiveStream = wr.GetResponseStream();
StreamReader reader = new StreamReader(receiveStream, Encoding.UTF8);
return reader.ReadToEnd();
and the interface declaration:
[OperationContract]
[WebInvoke(Method = "GET", RequestFormat = WebMessageFormat.Json, ResponseFormat = WebMessageFormat.Json)]
string DoWork();
Thank you for your time.
If you don’t want WCF to use any formatting in your response (i.e., not to convert it to a string, which is what you currently have), you can return a
Streamfrom the operation. That way WCF will return the bytes on the stream as they are (see example code below). You can read more about this at this post about the WCF “Raw” Programming Model.