How to send GUIDs efficiently (not as strings)
I have a collection containing a LOT of Data Transfer Objects that I need to send to a Silverlight client over WCF. I'm using the default DataContractSerializer and an HTTPS channel.
Here's an example of one type of DTO.
[DataContract(Namespace = Constants.OrgStructureNamespace)]
public class EntityInfo : IExtensibleDataObject
{
[DataMember] public Guid EntityID { get; set; }
[DataMember] public EntityType EntityType { get; set; }
[DataMember] public IList<Guid> EntityVersions { get; set; }
[DataMember] public IList<Guid> OrganisationStructures { get; set; }
#region IExtensibleDataObject Members
...
#endregion
}
The domain entities on the server side use GUIDs as primary keys. These get serialized to strings which are 36 bytes long. A GUID in binary form should only be 16 bytes long.
Is there a trick to get the DataContractSerializer serialize my GUIDs as binary rather than as the verbose strings to increase performance?
Try this:
[DataContract(Namespace = Constants.OrgStructureNamespace)]
public class EntityInfo : IExtensibleDataObject
{
public Guid EntityID { get; set; }
[DataMember(Name="EntityID")]
byte[] EntityIDBytes
{
get { return this.EntityID.ToByteArray(); }
set { this.EntityID = new Guid(value); }
}
[DataMember]
public EntityType EntityType { get; set; }
[DataMember]
public IList<Guid> EntityVersions { get; set; }
[DataMember]
public IList<Guid> OrganisationStructures { get; set; }
#region IExtensibleDataObject Members
// ...
#endregion
}
It looks like the DataContractSerializer handles byte arrays by Base64-encoding them, whereas it appears to just use the Guid.ToString method for Guids.
There is no way that this can be overcome from what I know. Guids are not universally understood by all languages. Therefore they are serialized into a more interoperable format, string
on your service side convert it back to a guid from a string and that should take care of it
var g = new Guid(string);
unless you specifically tell the system what you want it to serialize the guid is then i believe it will choose string
How about removing the DataMember attribute from your Guid-valued property, and adding instead a new string-valued DataMember property to represent whatever serialized form you want. Then implement the serialization and deserialization of the Guid field in the property get & set of the new property.
For example, you might serialize your 16-byte representation as a Base64 encoded string.
链接地址: http://www.djcxy.com/p/48842.html上一篇: CDATA真的有必要吗?
下一篇: 如何有效地发送GUID(而不是字符串)