|
| 1 | +// Copyright (c) .NET Foundation. All rights reserved. |
| 2 | +// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. |
| 3 | + |
| 4 | +using System; |
| 5 | +using System.Collections.Concurrent; |
| 6 | +using System.Collections.Generic; |
| 7 | +using System.Diagnostics; |
| 8 | +using System.IO; |
| 9 | +using System.Linq; |
| 10 | +using System.Reflection; |
| 11 | +using Microsoft.AspNetCore.Mvc.Formatters; |
| 12 | +using Microsoft.Extensions.Internal; |
| 13 | +using Newtonsoft.Json; |
| 14 | +using Newtonsoft.Json.Bson; |
| 15 | +using Newtonsoft.Json.Linq; |
| 16 | + |
| 17 | +namespace Microsoft.AspNetCore.Mvc.ViewFeatures.Internal |
| 18 | +{ |
| 19 | + public class TempDataSerializer |
| 20 | + { |
| 21 | + private readonly JsonSerializer _jsonSerializer = |
| 22 | + JsonSerializer.Create(JsonSerializerSettingsProvider.CreateSerializerSettings()); |
| 23 | + |
| 24 | + private static readonly MethodInfo _convertArrayMethodInfo = typeof(TempDataSerializer).GetMethod( |
| 25 | + nameof(ConvertArray), BindingFlags.Static | BindingFlags.NonPublic); |
| 26 | + private static readonly MethodInfo _convertDictionaryMethodInfo = typeof(TempDataSerializer).GetMethod( |
| 27 | + nameof(ConvertDictionary), BindingFlags.Static | BindingFlags.NonPublic); |
| 28 | + |
| 29 | + private static readonly ConcurrentDictionary<Type, Func<JArray, object>> _arrayConverters = |
| 30 | + new ConcurrentDictionary<Type, Func<JArray, object>>(); |
| 31 | + private static readonly ConcurrentDictionary<Type, Func<JObject, object>> _dictionaryConverters = |
| 32 | + new ConcurrentDictionary<Type, Func<JObject, object>>(); |
| 33 | + |
| 34 | + private static readonly Dictionary<JTokenType, Type> _tokenTypeLookup = new Dictionary<JTokenType, Type> |
| 35 | + { |
| 36 | + { JTokenType.String, typeof(string) }, |
| 37 | + { JTokenType.Integer, typeof(int) }, |
| 38 | + { JTokenType.Boolean, typeof(bool) }, |
| 39 | + { JTokenType.Float, typeof(float) }, |
| 40 | + { JTokenType.Guid, typeof(Guid) }, |
| 41 | + { JTokenType.Date, typeof(DateTime) }, |
| 42 | + { JTokenType.TimeSpan, typeof(TimeSpan) }, |
| 43 | + { JTokenType.Uri, typeof(Uri) }, |
| 44 | + }; |
| 45 | + |
| 46 | + public IDictionary<string, object> Deserialize(byte[] value) |
| 47 | + { |
| 48 | + Dictionary<string, object> tempDataDictionary = null; |
| 49 | + |
| 50 | + using (var memoryStream = new MemoryStream(value)) |
| 51 | + using (var writer = new BsonReader(memoryStream)) |
| 52 | + { |
| 53 | + tempDataDictionary = _jsonSerializer.Deserialize<Dictionary<string, object>>(writer); |
| 54 | + if (tempDataDictionary == null) |
| 55 | + { |
| 56 | + return new Dictionary<string, object>(StringComparer.OrdinalIgnoreCase); |
| 57 | + } |
| 58 | + } |
| 59 | + |
| 60 | + var convertedDictionary = new Dictionary<string, object>( |
| 61 | + tempDataDictionary, |
| 62 | + StringComparer.OrdinalIgnoreCase); |
| 63 | + foreach (var item in tempDataDictionary) |
| 64 | + { |
| 65 | + var jArrayValue = item.Value as JArray; |
| 66 | + var jObjectValue = item.Value as JObject; |
| 67 | + if (jArrayValue != null && jArrayValue.Count > 0) |
| 68 | + { |
| 69 | + var arrayType = jArrayValue[0].Type; |
| 70 | + Type returnType; |
| 71 | + if (_tokenTypeLookup.TryGetValue(arrayType, out returnType)) |
| 72 | + { |
| 73 | + var arrayConverter = _arrayConverters.GetOrAdd(returnType, type => |
| 74 | + { |
| 75 | + return (Func<JArray, object>)_convertArrayMethodInfo |
| 76 | + .MakeGenericMethod(type) |
| 77 | + .CreateDelegate(typeof(Func<JArray, object>)); |
| 78 | + }); |
| 79 | + var result = arrayConverter(jArrayValue); |
| 80 | + |
| 81 | + convertedDictionary[item.Key] = result; |
| 82 | + } |
| 83 | + else |
| 84 | + { |
| 85 | + var message = Resources.FormatTempData_CannotDeserializeToken(nameof(JToken), arrayType); |
| 86 | + throw new InvalidOperationException(message); |
| 87 | + } |
| 88 | + } |
| 89 | + else if (jObjectValue != null) |
| 90 | + { |
| 91 | + if (!jObjectValue.HasValues) |
| 92 | + { |
| 93 | + convertedDictionary[item.Key] = null; |
| 94 | + continue; |
| 95 | + } |
| 96 | + |
| 97 | + var jTokenType = jObjectValue.Properties().First().Value.Type; |
| 98 | + Type valueType; |
| 99 | + if (_tokenTypeLookup.TryGetValue(jTokenType, out valueType)) |
| 100 | + { |
| 101 | + var dictionaryConverter = _dictionaryConverters.GetOrAdd(valueType, type => |
| 102 | + { |
| 103 | + return (Func<JObject, object>)_convertDictionaryMethodInfo |
| 104 | + .MakeGenericMethod(type) |
| 105 | + .CreateDelegate(typeof(Func<JObject, object>)); |
| 106 | + }); |
| 107 | + var result = dictionaryConverter(jObjectValue); |
| 108 | + |
| 109 | + convertedDictionary[item.Key] = result; |
| 110 | + } |
| 111 | + else |
| 112 | + { |
| 113 | + var message = Resources.FormatTempData_CannotDeserializeToken(nameof(JToken), jTokenType); |
| 114 | + throw new InvalidOperationException(message); |
| 115 | + } |
| 116 | + } |
| 117 | + else if (item.Value is long) |
| 118 | + { |
| 119 | + var longValue = (long)item.Value; |
| 120 | + if (longValue >= int.MinValue && longValue <= int.MaxValue) |
| 121 | + { |
| 122 | + // BsonReader casts all ints to longs. We'll attempt to work around this by force converting |
| 123 | + // longs to ints when there's no loss of precision. |
| 124 | + convertedDictionary[item.Key] = (int)longValue; |
| 125 | + } |
| 126 | + } |
| 127 | + } |
| 128 | + |
| 129 | + return convertedDictionary ?? new Dictionary<string, object>(StringComparer.OrdinalIgnoreCase); |
| 130 | + } |
| 131 | + |
| 132 | + public byte[] Serialize(IDictionary<string, object> values) |
| 133 | + { |
| 134 | + var hasValues = (values != null && values.Count > 0); |
| 135 | + if (hasValues) |
| 136 | + { |
| 137 | + foreach (var item in values.Values) |
| 138 | + { |
| 139 | + if (item != null) |
| 140 | + { |
| 141 | + // We want to allow only simple types to be serialized. |
| 142 | + EnsureObjectCanBeSerialized(item); |
| 143 | + } |
| 144 | + } |
| 145 | + |
| 146 | + using (var memoryStream = new MemoryStream()) |
| 147 | + { |
| 148 | + using (var writer = new BsonWriter(memoryStream)) |
| 149 | + { |
| 150 | + _jsonSerializer.Serialize(writer, values); |
| 151 | + return memoryStream.ToArray(); |
| 152 | + } |
| 153 | + } |
| 154 | + } |
| 155 | + else |
| 156 | + { |
| 157 | + return new byte[0]; |
| 158 | + } |
| 159 | + } |
| 160 | + |
| 161 | + public void EnsureObjectCanBeSerialized(object item) |
| 162 | + { |
| 163 | + var itemType = item.GetType(); |
| 164 | + Type actualType = null; |
| 165 | + |
| 166 | + if (itemType.IsArray) |
| 167 | + { |
| 168 | + itemType = itemType.GetElementType(); |
| 169 | + } |
| 170 | + else if (itemType.GetTypeInfo().IsGenericType) |
| 171 | + { |
| 172 | + if (ClosedGenericMatcher.ExtractGenericInterface(itemType, typeof(IList<>)) != null) |
| 173 | + { |
| 174 | + var genericTypeArguments = itemType.GenericTypeArguments; |
| 175 | + Debug.Assert(genericTypeArguments.Length == 1, "IList<T> has one generic argument"); |
| 176 | + actualType = genericTypeArguments[0]; |
| 177 | + } |
| 178 | + else if (ClosedGenericMatcher.ExtractGenericInterface(itemType, typeof(IDictionary<,>)) != null) |
| 179 | + { |
| 180 | + var genericTypeArguments = itemType.GenericTypeArguments; |
| 181 | + Debug.Assert( |
| 182 | + genericTypeArguments.Length == 2, |
| 183 | + "IDictionary<TKey, TValue> has two generic arguments"); |
| 184 | + |
| 185 | + // Throw if the key type of the dictionary is not string. |
| 186 | + if (genericTypeArguments[0] != typeof(string)) |
| 187 | + { |
| 188 | + var message = Resources.FormatTempData_CannotSerializeDictionary( |
| 189 | + typeof(TempDataSerializer).FullName, genericTypeArguments[0]); |
| 190 | + throw new InvalidOperationException(message); |
| 191 | + } |
| 192 | + else |
| 193 | + { |
| 194 | + actualType = genericTypeArguments[1]; |
| 195 | + } |
| 196 | + } |
| 197 | + } |
| 198 | + |
| 199 | + actualType = actualType ?? itemType; |
| 200 | + if (!IsSimpleType(actualType)) |
| 201 | + { |
| 202 | + var underlyingType = Nullable.GetUnderlyingType(actualType) ?? actualType; |
| 203 | + var message = Resources.FormatTempData_CannotSerializeType( |
| 204 | + typeof(TempDataSerializer).FullName, underlyingType); |
| 205 | + throw new InvalidOperationException(message); |
| 206 | + } |
| 207 | + } |
| 208 | + |
| 209 | + private static IList<TVal> ConvertArray<TVal>(JArray array) |
| 210 | + { |
| 211 | + return array.Values<TVal>().ToArray(); |
| 212 | + } |
| 213 | + |
| 214 | + private static IDictionary<string, TVal> ConvertDictionary<TVal>(JObject jObject) |
| 215 | + { |
| 216 | + var convertedDictionary = new Dictionary<string, TVal>(StringComparer.Ordinal); |
| 217 | + foreach (var item in jObject) |
| 218 | + { |
| 219 | + convertedDictionary.Add(item.Key, jObject.Value<TVal>(item.Key)); |
| 220 | + } |
| 221 | + return convertedDictionary; |
| 222 | + } |
| 223 | + |
| 224 | + private static bool IsSimpleType(Type type) |
| 225 | + { |
| 226 | + var typeInfo = type.GetTypeInfo(); |
| 227 | + |
| 228 | + return typeInfo.IsPrimitive || |
| 229 | + typeInfo.IsEnum || |
| 230 | + type.Equals(typeof(decimal)) || |
| 231 | + type.Equals(typeof(string)) || |
| 232 | + type.Equals(typeof(DateTime)) || |
| 233 | + type.Equals(typeof(Guid)) || |
| 234 | + type.Equals(typeof(DateTimeOffset)) || |
| 235 | + type.Equals(typeof(TimeSpan)) || |
| 236 | + type.Equals(typeof(Uri)); |
| 237 | + } |
| 238 | + } |
| 239 | +} |
0 commit comments