1: public class MyJsonValueProviderFactory : ValueProviderFactory
2: {
3: public override IValueProvider GetValueProvider(ControllerContext controllerContext)
4: {
5: if (controllerContext == null)
6: {
7: throw new ArgumentNullException("controllerContext");
8: }
9:
10: if (!controllerContext.HttpContext.Request.ContentType.StartsWith(
11: "application/json", StringComparison.OrdinalIgnoreCase))
12: {
13: return null;
14: }
15:
16:
17: object value = Deserialize(controllerContext.RequestContext.HttpContext.Request.InputStream);
18:
19: if (value == null)
20: {
21: return null;
22: }
23:
24: var bag = new Dictionary<string, object>(StringComparer.OrdinalIgnoreCase);
25:
26: PopulateBag(bag, string.Empty, value);
27:
28: return new DictionaryValueProvider<object>(bag, CultureInfo.CurrentCulture);
29: }
30:
31: private static object Deserialize(Stream stream)
32: {
33: string str = new StreamReader(stream).ReadToEnd();
34:
35: if (string.IsNullOrEmpty(str))
36: {
37: return null;
38: }
39:
40: var serializer = new JavaScriptSerializer(new MySpecialTypeResolver());
41:
42: return serializer.DeserializeObject(str);
43: }
44:
45: private static void PopulateBag(Dictionary<string, object> bag, string prefix, object source)
46: {
47: var dictionary = source as IDictionary<string, object>;
48: if (dictionary != null)
49: {
50: foreach (var entry in dictionary)
51: {
52: PopulateBag(bag, CreatePropertyPrefix(prefix, entry.Key), entry.Value);
53: }
54: }
55: else
56: {
57: var list = source as IList;
58: if (list != null)
59: {
60: for (int i = 0; i < list.Count; i++)
61: {
62: PopulateBag(bag, CreateArrayItemPrefix(prefix, i), list[i]);
63: }
64: }
65: else
66: {
67: bag[prefix] = source;
68: }
69: }
70: }
71:
72: private static string CreatePropertyPrefix(string prefix, string propertyName)
73: {
74: if (!string.IsNullOrEmpty(prefix))
75: {
76: return (prefix + "." + propertyName);
77: }
78: return propertyName;
79: }
80:
81: private static string CreateArrayItemPrefix(string prefix, int index)
82: {
83: return (prefix + "[" + index.ToString(CultureInfo.InvariantCulture) + "]");
84: }
85: }