Files
telegram-bot/Core/SerializationBinder.cs
CrazyHackGUT 920148e05b add Uri parser, add ISerializationBinder
ISerializationBinder is added only in whitelist mode. Types for whitelisting should be registered manually via new API `Module.StartAsync()` or attribute `AllowedSerializableType(name)`
2024-05-29 00:19:30 +03:00

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];
}
}
}