简体   繁体   中英

Easiest way to serialize and send an object graph over WCF web service

what is the easiest way to send complex graphs of arbitrary data types from a WCF service to a silverlight client for instance? Here the DataContractSerializer is mentioned as the default serialization engine for WCF. It also says that "All publicly visible types that have a constructor that does not have parameters" can be serialized. This sounds to me like it would be possible to send arbitrary types over a WCF service. Is this true? No need for DataContracts, XmlElement attributes and things like that? Supposed it is true, which limitations on the client side exist (only clients which use (a subset) of the .NET framework for instance)?

Additionally it would be really nice if you could tell me, what the best stream would be to use in conjunction with DataContractSerializer.WriteObject(Stream stream, Object graph) for a Silverlight client.

Yes, it's true, you don't need to decorate the class with [DataContract], [Serializable], [Xml...] to have WCF serialize it. You can send arbitrary types as long as they follow a certain pattern (parameterless constructor, only serializing public fields / properties). There's a good article about POCO (plain old CLR objects) serialziation in WCF at http://www.pluralsight-training.net/community/blogs/aaron/archive/2008/05/13/50934.aspx .

As far as limitations on other clients, such as Silverlight, if the types are supported in the client, then it should work as well.

And for your last question, it doesn't really matter (as long as you can write to the stream). If you want to serialize an object to a file (in the Silverlight isolated storage), you'll likely end up using a FileStream ; if you want to serialize an object over the network directly, you may use the stream returned by HttpWebRequest.EndGetRequestStream ; if you want to do some in-memory manipulation, you may use a MemoryStream. But it really doesn't matter for the serializer. For the DCS, it's just a Stream.

One more thing, if you have a WCF service and are consuming it using Silverlight (for example, by using the Add Service Reference - ASR - to create a proxy to it), you don't need to worry about serialization - the proxy generated by the ASR wizard will use the internal WCF classes to handle the serialization for you, all you need to do is to call the methods in the proxy passing the objects directly.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM