This repository has been archived by the owner on Nov 25, 2019. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 104
/
JsonMediaTypeFormatter.cs
410 lines (366 loc) · 16.4 KB
/
JsonMediaTypeFormatter.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
// Copyright (c) Microsoft Open Technologies, Inc. All rights reserved. See License.txt in the project root for license information.
using System.Collections.Concurrent;
using System.Diagnostics.CodeAnalysis;
using System.Diagnostics.Contracts;
using System.IO;
using System.Net.Http.Headers;
using System.Net.Http.Internal;
using System.Runtime.Serialization;
using System.Runtime.Serialization.Json;
using System.Text;
using System.Threading.Tasks;
using System.Web.Http;
using System.Xml;
using Newtonsoft.Json;
using Newtonsoft.Json.Serialization;
namespace System.Net.Http.Formatting
{
/// <summary>
/// <see cref="MediaTypeFormatter"/> class to handle Json.
/// </summary>
public class JsonMediaTypeFormatter : MediaTypeFormatter
{
private JsonSerializerSettings _jsonSerializerSettings;
private int _maxDepth = FormattingUtilities.DefaultMaxDepth;
#if !NETFX_CORE
private ConcurrentDictionary<Type, DataContractJsonSerializer> _dataContractSerializerCache = new ConcurrentDictionary<Type, DataContractJsonSerializer>();
private readonly IContractResolver _defaultContractResolver;
private XmlDictionaryReaderQuotas _readerQuotas = FormattingUtilities.CreateDefaultReaderQuotas();
private RequestHeaderMapping _requestHeaderMapping;
#endif
/// <summary>
/// Initializes a new instance of the <see cref="JsonMediaTypeFormatter"/> class.
/// </summary>
public JsonMediaTypeFormatter()
{
// Set default supported media types
SupportedMediaTypes.Add(MediaTypeConstants.ApplicationJsonMediaType);
SupportedMediaTypes.Add(MediaTypeConstants.TextJsonMediaType);
// Initialize serializer
#if !NETFX_CORE
_defaultContractResolver = new JsonContractResolver(this);
#endif
_jsonSerializerSettings = CreateDefaultSerializerSettings();
// Set default supported character encodings
SupportedEncodings.Add(new UTF8Encoding(encoderShouldEmitUTF8Identifier: false, throwOnInvalidBytes: true));
SupportedEncodings.Add(new UnicodeEncoding(bigEndian: false, byteOrderMark: true, throwOnInvalidBytes: true));
#if !NETFX_CORE
_requestHeaderMapping = new XmlHttpRequestHeaderMapping();
MediaTypeMappings.Add(_requestHeaderMapping);
#endif
}
/// <summary>
/// Gets the default media type for Json, namely "application/json".
/// </summary>
/// <remarks>
/// The default media type does not have any <c>charset</c> parameter as
/// the <see cref="Encoding"/> can be configured on a per <see cref="JsonMediaTypeFormatter"/>
/// instance basis.
/// </remarks>
/// <value>
/// Because <see cref="MediaTypeHeaderValue"/> is mutable, the value
/// returned will be a new instance every time.
/// </value>
public static MediaTypeHeaderValue DefaultMediaType
{
get { return MediaTypeConstants.ApplicationJsonMediaType; }
}
/// <summary>
/// Gets or sets the <see cref="JsonSerializerSettings"/> used to configure the <see cref="JsonSerializer"/>.
/// </summary>
public JsonSerializerSettings SerializerSettings
{
get { return _jsonSerializerSettings; }
set
{
if (value == null)
{
throw Error.ArgumentNull("value");
}
_jsonSerializerSettings = value;
}
}
#if !NETFX_CORE
/// <summary>
/// Gets or sets a value indicating whether to use <see cref="DataContractJsonSerializer"/> by default.
/// </summary>
/// <value>
/// <c>true</c> if use <see cref="DataContractJsonSerializer"/> by default; otherwise, <c>false</c>. The default is <c>false</c>.
/// </value>
public bool UseDataContractJsonSerializer { get; set; }
#endif
/// <summary>
/// Gets or sets a value indicating whether to indent elements when writing data.
/// </summary>
public bool Indent { get; set; }
#if !NETFX_CORE
/// <summary>
/// Gets or sets the maximum depth allowed by this formatter.
/// </summary>
public int MaxDepth
{
get
{
return _maxDepth;
}
set
{
if (value < FormattingUtilities.DefaultMinDepth)
{
throw Error.ArgumentMustBeGreaterThanOrEqualTo("value", value, FormattingUtilities.DefaultMinDepth);
}
_maxDepth = value;
_readerQuotas.MaxDepth = value;
}
}
#endif
/// <summary>
/// Creates a <see cref="JsonSerializerSettings"/> instance with the default settings used by the <see cref="JsonMediaTypeFormatter"/>.
/// </summary>
[SuppressMessage("Microsoft.Performance", "CA1822:MarkMembersAsStatic", Justification = "This could only be static half the time.")]
public JsonSerializerSettings CreateDefaultSerializerSettings()
{
return new JsonSerializerSettings()
{
#if !NETFX_CORE
ContractResolver = _defaultContractResolver,
#endif
MissingMemberHandling = MissingMemberHandling.Ignore,
// Do not change this setting
// Setting this to None prevents Json.NET from loading malicious, unsafe, or security-sensitive types
TypeNameHandling = TypeNameHandling.None
};
}
/// <summary>
/// Determines whether this <see cref="JsonMediaTypeFormatter"/> can read objects
/// of the specified <paramref name="type"/>.
/// </summary>
/// <param name="type">The type of object that will be read.</param>
/// <returns><c>true</c> if objects of this <paramref name="type"/> can be read, otherwise <c>false</c>.</returns>
public override bool CanReadType(Type type)
{
if (type == null)
{
throw Error.ArgumentNull("type");
}
#if !NETFX_CORE
if (UseDataContractJsonSerializer)
{
// If there is a registered non-null serializer, we can support this type.
DataContractJsonSerializer serializer =
_dataContractSerializerCache.GetOrAdd(type, (t) => CreateDataContractSerializer(t, throwOnError: false));
// Null means we tested it before and know it is not supported
return serializer != null;
}
else
#endif
{
return true;
}
}
/// <summary>
/// Determines whether this <see cref="JsonMediaTypeFormatter"/> can write objects
/// of the specified <paramref name="type"/>.
/// </summary>
/// <param name="type">The type of object that will be written.</param>
/// <returns><c>true</c> if objects of this <paramref name="type"/> can be written, otherwise <c>false</c>.</returns>
public override bool CanWriteType(Type type)
{
if (type == null)
{
throw Error.ArgumentNull("type");
}
#if !NETFX_CORE
if (UseDataContractJsonSerializer)
{
MediaTypeFormatter.TryGetDelegatingTypeForIQueryableGenericOrSame(ref type);
// If there is a registered non-null serializer, we can support this type.
object serializer =
_dataContractSerializerCache.GetOrAdd(type, (t) => CreateDataContractSerializer(t, throwOnError: false));
// Null means we tested it before and know it is not supported
return serializer != null;
}
else
#endif
{
return true;
}
}
/// <summary>
/// Called during deserialization to read an object of the specified <paramref name="type"/>
/// from the specified <paramref name="readStream"/>.
/// </summary>
/// <param name="type">The type of object to read.</param>
/// <param name="readStream">The <see cref="Stream"/> from which to read.</param>
/// <param name="content">The <see cref="HttpContent"/> for the content being written.</param>
/// <param name="formatterLogger">The <see cref="IFormatterLogger"/> to log events to.</param>
/// <returns>A <see cref="Task"/> whose result will be the object instance that has been read.</returns>
public override Task<object> ReadFromStreamAsync(Type type, Stream readStream, HttpContent content, IFormatterLogger formatterLogger)
{
if (type == null)
{
throw Error.ArgumentNull("type");
}
if (readStream == null)
{
throw Error.ArgumentNull("readStream");
}
return TaskHelpers.RunSynchronously<object>(() =>
{
HttpContentHeaders contentHeaders = content == null ? null : content.Headers;
// If content length is 0 then return default value for this type
if (contentHeaders != null && contentHeaders.ContentLength == 0)
{
return GetDefaultValueForType(type);
}
// Get the character encoding for the content
Encoding effectiveEncoding = SelectCharacterEncoding(contentHeaders);
try
{
#if !NETFX_CORE
if (UseDataContractJsonSerializer)
{
DataContractJsonSerializer dataContractSerializer = GetDataContractSerializer(type);
using (XmlReader reader = JsonReaderWriterFactory.CreateJsonReader(new NonClosingDelegatingStream(readStream), effectiveEncoding, _readerQuotas, null))
{
return dataContractSerializer.ReadObject(reader);
}
}
else
#endif
{
using (JsonTextReader jsonTextReader = new JsonTextReader(new StreamReader(readStream, effectiveEncoding)) { CloseInput = false, MaxDepth = _maxDepth })
{
JsonSerializer jsonSerializer = JsonSerializer.Create(_jsonSerializerSettings);
if (formatterLogger != null)
{
// Error must always be marked as handled
// Failure to do so can cause the exception to be rethrown at every recursive level and overflow the stack for x64 CLR processes
jsonSerializer.Error += (sender, e) =>
{
Exception exception = e.ErrorContext.Error;
formatterLogger.LogError(e.ErrorContext.Path, exception);
e.ErrorContext.Handled = true;
};
}
return jsonSerializer.Deserialize(jsonTextReader, type);
}
}
}
catch (Exception e)
{
if (formatterLogger == null)
{
throw;
}
formatterLogger.LogError(String.Empty, e);
return GetDefaultValueForType(type);
}
});
}
/// <summary>
/// Called during serialization to write an object of the specified <paramref name="type"/>
/// to the specified <paramref name="writeStream"/>.
/// </summary>
/// <param name="type">The type of object to write.</param>
/// <param name="value">The object to write.</param>
/// <param name="writeStream">The <see cref="Stream"/> to which to write.</param>
/// <param name="content">The <see cref="HttpContent"/> for the content being written.</param>
/// <param name="transportContext">The <see cref="TransportContext"/>.</param>
/// <returns>A <see cref="Task"/> that will write the value to the stream.</returns>
public override Task WriteToStreamAsync(Type type, object value, Stream writeStream, HttpContent content, TransportContext transportContext)
{
if (type == null)
{
throw Error.ArgumentNull("type");
}
if (writeStream == null)
{
throw Error.ArgumentNull("writeStream");
}
#if !NETFX_CORE
if (UseDataContractJsonSerializer && Indent)
{
throw Error.NotSupported(Properties.Resources.UnsupportedIndent, typeof(DataContractJsonSerializer));
}
#endif
return TaskHelpers.RunSynchronously(() =>
{
Encoding effectiveEncoding = SelectCharacterEncoding(content == null ? null : content.Headers);
#if !NETFX_CORE
if (UseDataContractJsonSerializer)
{
if (MediaTypeFormatter.TryGetDelegatingTypeForIQueryableGenericOrSame(ref type))
{
if (value != null)
{
value = MediaTypeFormatter.GetTypeRemappingConstructor(type).Invoke(new object[] { value });
}
}
DataContractJsonSerializer dataContractSerializer = GetDataContractSerializer(type);
using (XmlWriter writer = JsonReaderWriterFactory.CreateJsonWriter(writeStream, effectiveEncoding, ownsStream: false))
{
dataContractSerializer.WriteObject(writer, value);
}
}
else
#endif
{
using (JsonTextWriter jsonTextWriter = new JsonTextWriter(new StreamWriter(writeStream, effectiveEncoding)) { CloseOutput = false })
{
if (Indent)
{
jsonTextWriter.Formatting = Newtonsoft.Json.Formatting.Indented;
}
JsonSerializer jsonSerializer = JsonSerializer.Create(_jsonSerializerSettings);
jsonSerializer.Serialize(jsonTextWriter, value);
jsonTextWriter.Flush();
}
}
});
}
#if !NETFX_CORE
private static DataContractJsonSerializer CreateDataContractSerializer(Type type, bool throwOnError)
{
if (type == null)
{
throw Error.ArgumentNull("type");
}
DataContractJsonSerializer serializer = null;
Exception exception = null;
try
{
// Verify that type is a valid data contract by forcing the serializer to try to create a data contract
FormattingUtilities.XsdDataContractExporter.GetRootElementName(type);
serializer = new DataContractJsonSerializer(type);
}
catch (InvalidDataContractException invalidDataContractException)
{
exception = invalidDataContractException;
}
if (exception != null)
{
if (throwOnError)
{
throw Error.InvalidOperation(exception, Properties.Resources.SerializerCannotSerializeType,
typeof(DataContractJsonSerializer).Name,
type.Name);
}
}
return serializer;
}
private DataContractJsonSerializer GetDataContractSerializer(Type type)
{
Contract.Assert(type != null, "Type cannot be null");
DataContractJsonSerializer serializer =
_dataContractSerializerCache.GetOrAdd(type, (t) => CreateDataContractSerializer(type, throwOnError: true));
if (serializer == null)
{
// A null serializer means the type cannot be serialized
throw Error.InvalidOperation(Properties.Resources.SerializerCannotSerializeType, typeof(DataContractJsonSerializer).Name, type.Name);
}
return serializer;
}
#endif
}
}