tags:

views:

714

answers:

3

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?

+1  A: 

If you are using a xml based binding, then I believe there is no way to do that. A simple solution in that case would to just have part of the message flag if there was a failure, and store the failure information somewhere if needed. For a JSON binding you may be able to use a method that returns an object, then return two different types of objects. If I remember correctly (which is rare), that is possible because the JavaScriptSerializer class uses reflection if the object is clean of serialization attributes.

scmccart
+1  A: 

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

Chuck
+1  A: 

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 source code 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.

JarrettV
I didn't find that file (RestAtomPubService.cs) in the source, did I miss it or has it been removed? Thanks.
Kevin Berridge
We've since moved away from WCF for REST because it was not flexible enough for our needs. I think the file should still be there in history.
JarrettV