#REST-ish API with #WCF, part 2 Responses

If you thought the headache was over, I’ve got a treat for you. It’s not. But the “solution” isn’t far away though and quite straight forward. This hack is roughly the same like when working with the requests.

There is a built in constraint in WCF that you can only work with basically Json or XML. Or raw. That’s what all this fuzz is about. Too bad they didn’t make it obvious or easy to implement. The short explanation is however that if you request/return a Stream, it forces the WCF framework to abandon all it’s nifty things and smart moves and leaves it up to you to decide. So, set the return type to Stream, do your thing, serialization and what not. And send it out. The response will not get wrapped within the return type.

public Stream Check(Stream request){
  var json = ReadStreamAndDeserialize(request);
  //do stuff
  var jsonResponse = Serialize(response);
  WebOperationContext.Current.OutgoingResponse.ContentType = "application/json; charset=utf-8";
  return new MemoryStream(Encoding.UTF8.GetBytes(jsonResponse));

Why do this?

In our case we needed to serialize different types a bit differently and couldn’t get the internal serializer to work quite as we wanted. But also imagine that you could serve images back. You can even stream images back. And what if it is a file service? You could serve back whatever contenttype you like, and make it different depending on the file served. It does add some nice features you can work with to extend your options.

What you should also consider is what it does. In this case we make heavily use of the http protocol as opposed to others, which means it limits your options of just serving data over any protocol. It also takes you closer to the protocol you are working with, which can be both a blessing and a curse. If you don’t know what you are doing, you could end up in a lot of trouble and just having to write hack upon hack upon hack.

Check out the complete working example on GitHub.

Read more

Tagged , , ,