Skip to content

Instantly share code, notes, and snippets.

@pwhe23
Created October 12, 2020 18:22
Show Gist options
  • Select an option

  • Save pwhe23/4f3c37514621ef499ac9d030a38165b7 to your computer and use it in GitHub Desktop.

Select an option

Save pwhe23/4f3c37514621ef499ac9d030a38165b7 to your computer and use it in GitHub Desktop.
JsonTempDataSerializer
using System;
using System.Collections.Generic;
using System.IO;
using Microsoft.AspNetCore.Mvc.ViewFeatures.Infrastructure;
using Newtonsoft.Json;
using Newtonsoft.Json.Bson;
public class JsonTempDataSerializer : TempDataSerializer
{
private readonly JsonSerializer _jsonSerializer = JsonSerializer.CreateDefault(new JsonSerializerSettings
{
TypeNameHandling = TypeNameHandling.All, // This may have security implications
});
public override byte[] Serialize(IDictionary<string, object>? values)
{
var hasValues = values?.Count > 0;
if (!hasValues)
return Array.Empty<byte>();
using var memoryStream = new MemoryStream();
using var writer = new BsonDataWriter(memoryStream);
_jsonSerializer.Serialize(writer, values);
return memoryStream.ToArray();
}
public override IDictionary<string, object> Deserialize(byte[] unprotectedData)
{
using var memoryStream = new MemoryStream(unprotectedData);
using var reader = new BsonDataReader(memoryStream);
var tempDataDictionary = _jsonSerializer.Deserialize<Dictionary<string, object>>(reader)
?? new Dictionary<string, object>(StringComparer.OrdinalIgnoreCase);
return tempDataDictionary;
}
};
services.AddSingleton<TempDataSerializer, JsonTempDataSerializer>();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment