WCF & Json - Complete Output Control

Posted on January 7, 2008 01:46 by Mamanze

One issue I've run into a couple times while working on restive WCF messages is the need to have complete control over the output. For example, when I wanted to generate a custom proxy for my rest service, I wanted to take over the /jsdebug UriTemplate and output plain JS (not JSON).

 

When I initially wrote that proxy generator, I used some reflection to hack the XML Writer into doing what I needed. Then, digging around the JSON Error Handlers, I noticed the framework had an internal class to output raw text. What it boils down to is:

 

Byte[] buffer = Encoding.UTF8.GetBytes(messageBody);

writer.WriteStartElement("Binary", string.Empty);
writer.WriteValue(buffer);
writer.WriteEndElement();

 

Unfortunately, they take a very difficult route of doing that. To ease things, I've created this RawMessage class which wraps up a string and spits it out in raw format:

 

 

Hopefully that'll save someone a few minutes in the future.

Be the first to rate this post

  • Currently 0/5 Stars.
  • 1
  • 2
  • 3
  • 4
  • 5

Related posts

Comments

April 15. 2008 16:37

Armen Jamkotchian

Hello,
My RESTful WCF service is based on WebHttpBinding. Depending on the request type (XML or JSON) the output is serialized either as JSON or as XML.
The problem I have is that when an error occures, I return a special error message. Becaouse of the exception, the message does not hit webMessageEncoding channel. The following code constructs the message:

System.ServiceModel.Channels.Message errorMessage = System.ServiceModel.Channels.Message.CreateMessage(MessageVersion.None, "xyz", new SimpleMessageBody());

public class SimpleMessageBody : BodyWriter {

public SimpleMessageBody()
: base(true) {

}

protected override void OnWriteBodyContents(XmlDictionaryWriter writer) {
Byte[] buffer = Encoding.UTF8.GetBytes("error message");
writer.WriteStartElement("Binary", string.Empty);
//writer.WriteValue("error message");
writer.WriteValue(buffer);
writer.WriteEndElement();
}
}

The output is an XML: <Binary>error message</Binary>

I need to have a string rather than an XML.
Do you have any suggestions?

Armen Jamkotchian us

Add comment


(Will show your Gravatar icon)  

  Country flag

[b][/b] - [i][/i] - [u][/u]- [quote][/quote]



Live preview

August 28. 2008 14:06