1: public class JsonpMediaTypeFormatter : JsonMediaTypeFormatter
2: {
3: public string Callback { get; private set; }
4:
5: public JsonpMediaTypeFormatter(string callback = null)
6: {
7: this.Callback = callback;
8: }
9:
10: public override Task WriteToStreamAsync(Type type, object value, Stream writeStream, HttpContent content, TransportContext transportContext)
11: {
12: if (string.IsNullOrEmpty(this.Callback))
13: {
14: return base.WriteToStreamAsync(type, value, writeStream, content, transportContext);
15: }
16: try
17: {
18: this.WriteToStream(type, value, writeStream, content);
19: return Task.FromResult<AsyncVoid>(new AsyncVoid());
20: }
21: catch (Exception exception)
22: {
23: TaskCompletionSource<AsyncVoid> source = new TaskCompletionSource<AsyncVoid>();
24: source.SetException(exception);
25: return source.Task;
26: }
27: }
28:
29: private void WriteToStream(Type type, object value, Stream writeStream, HttpContent content)
30: {
31: JsonSerializer serializer = JsonSerializer.Create(this.SerializerSettings);
32: using(StreamWriter streamWriter = new StreamWriter(writeStream, this.SupportedEncodings.First()))
33: using (JsonTextWriter jsonTextWriter = new JsonTextWriter(streamWriter) { CloseOutput = false })
35: {
36: jsonTextWriter.WriteRaw(this.Callback + "(");
37: serializer.Serialize(jsonTextWriter, value);
38: jsonTextWriter.WriteRaw(")");
39: }
40: }
41:
42: public override MediaTypeFormatter GetPerRequestFormatterInstance(Type type, HttpRequestMessage request, MediaTypeHeaderValue mediaType)
43: {
44: if (request.Method != HttpMethod.Get)
45: {
46: return this;
47: }
48: string callback;
49: if (request.GetQueryNameValuePairs().ToDictionary(pair => pair.Key,
50: pair => pair.Value).TryGetValue("callback", out callback))
51: {
52: return new JsonpMediaTypeFormatter(callback);
53: }
54: return this;
55: }
56:
57: [StructLayout(LayoutKind.Sequential, Size = 1)]
58: private struct AsyncVoid
59: {}
60: }