【问题标题】:Deserialize Interface-Type反序列化接口类型
【发布时间】:2014-07-01 01:07:37
【问题描述】:

我有一个客户端-服务器-应用程序,我想将加密对象从服务器发送到客户端。

客户端正在向服务器发送请求,例如:

byte[] encryptedResponse = authenticationService.SendRequest(sessionId, requestData);

然后客户端得到一个加密的响应字节数组。然后他打电话

byte[] clearResponse = Cryptography.DecryptSymmetric(key, iv, encryptedResponse);

在 clearResponse 中现在是来自服务器的清除二进制序列化对象。

客户端和服务器共享一个接口库,其中包含 IUser-Interface,如下所示:

public interface IUser : ISerializable
{
   Guid UserId { get; }
   string Username { get; }
} 

服务器包含此接口的实现,如下所示:

[Serializable]
    internal class User : IUser
    {
        public User(){}

        public User(SerializationInfo info, StreamingContext context)
        {
            Id = Guid.Parse(info.GetString(XmlNodes.UserId));
            Username = info.GetString(XmlNodes.Username);
        }

        public Guid Id { get; set; }

        public string Username { get; set; }

        public void GetObjectData(SerializationInfo info, StreamingContext context)
        {
            info.AddValue(XmlNodes.UserId, Id.ToString());
            info.AddValue(XmlNodes.Username, Username);            
        }
    }

服务端使用如下代码为客户端序列化用户:

byte[] responseData;
IUser user = new User { Id = Guid.NewGuid(), Username = "Dummy" };
using(MemoryStream memoryStream = new MemoryStream())
{
  BinaryFormatter binaryFormatter = new BinaryFormatter();
  binaryFormatter.Serialize(memoryStream, user);
  responseData = memoryStream.ToArray();
}
// encrypt the responseData and send it to the client.

现在如果我尝试反序列化用户:

using(MemoryStream memoryStream = new MemoryStream(clearResponse))
{
  BinaryFormatter binaryFormatter = new BinaryFormatter();
  IUser user = (IUser)binaryFormatter.Deserialize(memoryStream)
}

我遇到了异常。

未处理的类型异常 'System.Runtime.Serialization.SerializationException' 发生在 mscorlib.dll

附加信息:程序集“用户,版本=1.0.0.0, Culture=neutral, PublicKeyToken=null" 找不到。

如何反序列化我只知道接口的类型?

【问题讨论】:

    标签: c# serialization binaryformatter


    【解决方案1】:

    不能使用BinaryFormatter,因为类型是数据的一部分。

    您可以使用XmlSerializer 并将生成的string 作为(可能已加密)byte[] 发送给客户端。那么客户端只需要一个“兼容类型”来反序列化它。

    如果您想坚持使用BinaryFormatter,您还可以将User 类型移动到共享库(如果还没有)并由服务器和客户端引用。

    【讨论】:

    • This answer 说可以,可能 OP 只是没有对定义 User 类型的程序集的引用。如果他添加了这一点(就像你在上一段中所说的那样),代码可能会开始正常工作。
    • @oleksii: 不是真的:This means that when the binary formatter **deserializes the object it knows its type**, builds the correct object and you can then cast that to an interface type that object implements. 在这个演员阵容中它不知道类型......
    • 是的。我没有对定义用户类型的程序集的引用。但是我的客户不允许知道这个程序集。是否有另一种方法可以将接口类型作为 byte[] 发送给客户端?
    • 我只知道使用XmlSerializer。您对这种方法有什么问题?
    猜你喜欢
    • 2010-12-08
    • 1970-01-01
    • 1970-01-01
    • 2012-12-09
    • 2015-11-04
    • 2021-09-09
    • 1970-01-01
    • 1970-01-01
    • 2016-02-04
    相关资源
    最近更新 更多