mirror of
https://github.com/Bubuni-Team/telegram-bot.git
synced 2026-07-31 00:29:24 +03:00
920148e05b
ISerializationBinder is added only in whitelist mode. Types for whitelisting should be registered manually via new API `Module.StartAsync()` or attribute `AllowedSerializableType(name)`
50 lines
1.4 KiB
C#
50 lines
1.4 KiB
C#
using Newtonsoft.Json.Serialization;
|
|
using System;
|
|
using System.Collections.Generic;
|
|
using System.Linq;
|
|
|
|
namespace Kruzya.TelegramBot.Core
|
|
{
|
|
public class SerializationBinder : ISerializationBinder
|
|
{
|
|
protected IDictionary<string, Type> _allowedTypes = new Dictionary<string, Type>();
|
|
|
|
public void RegisterAllowedType(string name, Type type)
|
|
{
|
|
if (_allowedTypes.ContainsKey(name))
|
|
{
|
|
throw new ArgumentException($"{name} is already registered", "name");
|
|
}
|
|
|
|
foreach (var knownType in _allowedTypes.Values)
|
|
{
|
|
if (type != knownType)
|
|
{
|
|
continue;
|
|
}
|
|
|
|
throw new ArgumentException($"{type.FullName} is already known type", "type");
|
|
}
|
|
|
|
_allowedTypes.Add(name, type);
|
|
}
|
|
|
|
public void RegisterAllowedType<T>(string name) where T : class
|
|
{
|
|
RegisterAllowedType(name, typeof(T));
|
|
}
|
|
|
|
public void BindToName(Type serializedType, out string assemblyName, out string typeName)
|
|
{
|
|
assemblyName = null;
|
|
typeName = _allowedTypes.Where(x => x.Value == serializedType)
|
|
.FirstOrDefault().Key;
|
|
}
|
|
|
|
public Type BindToType(string assemblyName, string typeName)
|
|
{
|
|
return _allowedTypes[typeName];
|
|
}
|
|
}
|
|
}
|