От: | vladpol | http://vlad-mislitel.livejournal.com/ | |
Дата: | 01.07.19 16:52 | ||
Оценка: |
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>
// Decompiled with JetBrains decompiler
// Type: System.Runtime.Serialization.Formatters.Binary.Converter
// Assembly: System.Runtime.Serialization.Formatters, Version=4.0.3.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a
// MVID: DE65D97E-45D3-4ECC-8EF5-5BBE1917DA67
// Assembly location: C:\Program Files\dotnet\shared\Microsoft.NETCore.App\2.1.11\System.Runtime.Serialization.Formatters.dll
using System.Globalization;
using System.Reflection;
namespace System.Runtime.Serialization.Formatters.Binary
{
internal static class 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;