Issue while Serialized in server project and deserialized in client project in c#

92 Views Asked by At

I am hosting API and client will be build by someone else and consume my API. But while testing I am getting below exception while deserialized in client project.

System.Runtime.Serialization.SerializationException: Unable to find assembly 'Gateway, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null'

I want to pass encrypted object while giving response in API. So first I am serializing it then encrypting. So while deserilized I am getting above error. Code at server

BinaryFormatter formatter = new BinaryFormatter();
using (MemoryStream ms = new MemoryStream())
{
    formatter.Serialize(ms, obj);
    return ms.ToArray();
}
    
1

There are 1 best solutions below

0
JonasH On

Please do not use BinaryFormatter, it is terrible in just about every way. It is slow, insecure and inflexible. And also obsoleted, due to the aforementioned reasons.

My understanding of BinaryFormtter is that it basically just dumps the memory representation of an object to file. This means that anything that changes this representation will break serialization. Including

  • Changes to class names or name spaces
  • Changes to .Net version (not every version, but can, and has, happened)
  • Any addition or removal of properties.

Your error most likely says that the serialized class Gateway cannot be found on the client. Just copying the class definition to your client project, like you could do with most serialization libraries, is not enough. You at the very least need to ensure namespaces match exactly, and it might be easier to just reference the exact same dll that was used for serialization.

But please use a sane serializer instead. Json is the most popular alternative, possibly combined with compression if you are concerned about space. If you want binary serialization, protobuf .net is a good alternative. But there are plenty more to chose from, these are just the ones I have most experience with.