Return raw json string in WCF

I want to use a certain format for the output of the data which isnโ€™t (natively) supported by WCF, such as XML or JSON.

Web method return a String together with ResponseFormat = WebMessageFormat.Json. It follow to the JSON encoding of the string.

Corresponds to http://www.json.org all double quotes in the string will be escaped using backslash.

The simplest way to return any kind of data is to change the output type of web method to Stream or Message (from System.ServiceModel.Channels) instead of String.

public Stream GetUsers()

{

//Code Here

return new MemoryStream(Encoding.UTF8.GetBytes(jsonresult));

}

The Web programming model introduced in WCF on .NET Framework 3.5 simplifies this task. The magic happens when the operation return type is of System.IO.Stream (the abstract class, not one of its concrete implementations).

By returning a stream, WCF assumes that the operation wants total control over the bytes that will be returned in the response, and will apply no formatting whatsoever in the data that is returned

Windows Communication Foundation (WCF) can send messages using either buffered or streamed transfers. In the default buffered-transfer mode, a message must be completely delivered before a receiver can read it.

In streaming transfer mode, the receiver can begin to process the message before it is completely delivered.

The streaming mode is useful when the information that is passed is lengthy and can be processed serially. Streaming mode is also useful when the message is too large to be entirely buffered.

Useful Links:

Happy Coding ๐Ÿ™‚

Advertisements

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