Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a way to return different types from a WCF REST method?

Tags:

rest

c#

.net

wcf

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?

like image 678
kgriffs Avatar asked Sep 26 '08 15:09

kgriffs


2 Answers

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

like image 85
Chuck Avatar answered Nov 18 '22 07:11

Chuck


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.

like image 44
JarrettV Avatar answered Nov 18 '22 07:11

JarrettV