.net - .NET Framework 到 .NET Core 迁移序列化问题
问题描述
我已将许多类库从 .NET Framework 4.5 移植到 .NET Standard 2.0。从 .NET Framework 4.8 控制台应用程序中使用这些库可以正常工作。但是,从 .NET Core 2.2 控制台应用程序引用库会导致以下异常:
SerializationException: Type 'System.Collections.Hashtable+SyncHashtable' in Assembly 'System.Runtime.Extensions, Version=4.2.1.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a' is not marked as serializable
带有堆栈跟踪
at System.Runtime.Serialization.Formatters.Binary.ObjectReader.CheckSerializable(Type t)
at System.Runtime.Serialization.Formatters.Binary.ObjectReader.ParseObject(ParseRecord pr)
at System.Runtime.Serialization.Formatters.Binary.ObjectReader.Parse(ParseRecord pr)
at System.Runtime.Serialization.Formatters.Binary.BinaryParser.ReadObjectWithMapTyped(BinaryHeaderEnum binaryHeaderEnum)
at System.Runtime.Serialization.Formatters.Binary.BinaryParser.Run()
at System.Runtime.Serialization.Formatters.Binary.ObjectReader.Deserialize(BinaryParser serParser, Boolean fCheck)
at System.Runtime.Serialization.Formatters.Binary.BinaryFormatter.Deserialize(Stream serializationStream, Boolean check)
at System.Runtime.Serialization.Formatters.Binary.BinaryFormatter.Deserialize(Stream serializationStream)
我对失败的框架的最内部调用代码是这样的:
public static object Deserialize(BinaryReader binaryReader)
{
BinaryReader binaryReader = new BinaryReader(inStream);
BinaryFormatter binaryFormatter = new BinaryFormatter();
return binaryFormatter.Deserialize(binaryReader.BaseStream);
}
有任何想法吗?
解决方案
来自 Microsoft 的回答:“在 .NET Core 中,可二进制序列化的类型比在 .NET Framework 中要少。这是设计使然,因为基于 BinaryFormatter 的序列化历来是脆弱的并且容易出现安全问题。SyncHashtable 当前不可序列化。但是,我们可能应该这样做。同时,您需要避免对其进行序列化。这可能意味着使用 Hashtable 并手动锁定而不是使用 SyncHashtable。或者可能(高级)使用 BinaryFormatter 的扩展机制来解决这个问题。”</p>
在 GitHub 上的对话:https ://github.com/dotnet/corefx/issues/37708#issuecomment-493641762
推荐阅读
- node.js - 如何在 sequelize index.ts 文件中导入模型
- php - Woocommerce - Var_dump() 返回计数,尽管类别错误
- php - 如何使用 Laravel Eloquent 更新 PostgresSQL 中 jsonb 列的多个“键”
- android - 绑定适配器中的多个视图
- html - 停止运行整个 web css 的行动画
- php - 如何使用模块 11 算法计算和获取数字
- javascript - 如何使用 DJANGO python 在 POSTGRESQL 数据库中保存 JSON 数组数据?
- javascript - 如何修复我的 Blazor 服务器应用程序文件下载过程?
- aws-sdk-go - AWS golang sdk v2 描述安全组新手问题
- php - 如何删除 Woo 商务订单列表中的货币?