如果我在.NetCoreApp中使用SerializationBinder
,则方法BindToType
从mscorlib
而不是System.Private.CoreLib
获得类型名类型
namespace BinaryFormatterTest{
class Program
{
static void Main(string[] args)
{
var runtimeType = new Dictionary<string, long?>{{"a",1}};
using (var memoryStream = new System.IO.MemoryStream())
{
var binaryFormatter = new System.Runtime.Serialization.Formatters.Binary.BinaryFormatter(){Binder = new AllowedTypesValidatorSerializationBinder()};
binaryFormatter.Serialize(memoryStream, runtimeType);
memoryStream.Seek(0, SeekOrigin.Begin);
var result = (Dictionary<string, long?>)binaryFormatter.Deserialize(memoryStream);
Console.WriteLine(result["a"]);
}
}
}
class AllowedTypesValidatorSerializationBinder : SerializationBinder
{
private static readonly Dictionary<string, Type> _knownTypesCache = new Dictionary<string, Type>(StringComparer.Ordinal)
{
{ typeof(string).FullName, typeof(string)},
{
typeof(Dictionary<string, long?>).FullName, typeof(Dictionary<string, long?>)
},
{
typeof(KeyValuePair<string, long?>).FullName, typeof(KeyValuePair<string, long?>)
},
};
public override Type BindToType(string assemblyName, string typeName)
{
Type t = null;
try
{
t = _knownTypesCache[typeName];
}
catch (KeyNotFoundException)
{
return null;
// throw new InvalidOperationException("Validation failed, type is not allowed: " + typeName);
}
return t;
}
}
}
所以我得到的名字是
System.Collections.Generic.Dictionary`2[[System.String, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089],[System.Nullable`1[[System.Int64, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]], mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]]
代替
[System.Collections.Generic.Dictionary`2[[System.String, System.Private.CoreLib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=7cec85d7bea7798e],[System.Nullable`1[[System.Int64, System.Private.CoreLib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=7cec85d7bea7798e]], System.Private.CoreLib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=7cec85d7bea7798e]], System.Collections.Generic.Dictionary`2[System.String,System.Nullable`1[System.Int64]]]} System.Collections.Generic.KeyValuePair<string, System.Type>
根本原因似乎在System.Runtime.Serialization.Formatters.Binary.Converter
类中:
internal static readonly Assembly s_urtAssembly = Assembly.Load("mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089");
internal static readonly string s_urtAssemblyString = Converter.s_urtAssembly.FullName;
还有其他人遇到同样的问题吗? 谢谢。