I am trying to write a web service to spec and it requires a different response body depending on whether the method completes successfully or not. I have tried creating two different DataContract classes, but how can I return them and have them serialized correctly?
The best way to indicate that your WCF web service has failed would be to throw a FaultException. There are settings in your service web.config files that allow the entire fault message to be passed to the client as part of the error.
Another approach may be to inherit both of your results from the same base class or interface. The service would return an instance of the base type. You can then use the KnownType attribute to inform the client that multiple types may be returned. Come to think of it, it might be possible to use Object as the base type, but I haven't tried it.
Failing either of those approaches, you can create a custom result object that contains both a result and error properties and your client can then decide which course of action to take. I had to use this approach for Silverlight 2 because Beta 2 does not yet fully support fault contracts. It's not pretty, I wouldn't normally recommend it, but if it's the only way that works or you feel it is the best approach for your situation...
If you are having troubles with ADO.NET Data Services, I have less experience there.
Here's some information on implementing FaultContracts
The answer is yes but it is tricky and you lose strong typing on your interface. If you return a Stream then the data could be xml, text, or even a binary image. For DataContract classes, you'd then serialize the data using the DataContractSerializer.
See the BlogSvc and more specifically the RestAtomPubService.cs WCF service for more details. Note, that source code will also show you how to accept different types of data into a WCF rest method which requires a content type mapper.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With