Created
June 26, 2019 06:12
-
-
Save seangwright/64b6fdbb0f7578517dbae8634733aae9 to your computer and use it in GitHub Desktop.
Custom Json Serialization for ASP.NET MVC
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/// <summary> | |
/// From https://github.com/garysharp/Disco/commit/1dfa3f4f15fe4fc093e90e4cd490dd06cc30cf07 | |
/// </summary> | |
public class JsonDotNetValueProviderFactory : ValueProviderFactory | |
{ | |
private readonly JsonSerializerSettings serializerSettings; | |
public JsonDotNetValueProviderFactory(JsonSerializerSettings serializerSettings) | |
{ | |
Guard.Against.Null(serializerSettings, nameof(serializerSettings)); | |
this.serializerSettings = serializerSettings; | |
} | |
public override IValueProvider GetValueProvider(ControllerContext controllerContext) | |
{ | |
Guard.Against.Null(controllerContext, nameof(controllerContext)); | |
var request = controllerContext.HttpContext.Request; | |
if (!request.ContentType.StartsWith("application/json", StringComparison.OrdinalIgnoreCase)) | |
{ | |
return null; | |
} | |
if (request.InputStream.Length == 0) | |
{ | |
return null; | |
} | |
var jsonSerializer = JsonSerializer.Create(serializerSettings); | |
jsonSerializer.Converters.Add(new ExpandoObjectConverter()); | |
using (var streamReader = new StreamReader(request.InputStream, Encoding.UTF8, true, 0x400, true)) | |
{ | |
using (var jsonReader = new JsonTextReader(streamReader)) | |
{ | |
var bodyObject = jsonSerializer.Deserialize<ExpandoObject>(jsonReader); | |
return new DictionaryValueProvider<object>(bodyObject, CultureInfo.CurrentCulture); | |
} | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment