PageRenderTime 89ms CodeModel.GetById 77ms app.highlight 7ms RepoModel.GetById 2ms app.codeStats 0ms

/WCFWebApi/prototype/Microsoft.ApplicationServer.HttpEnhancements/Microsoft/ApplicationServer/Http/JsonpMediaTypeFormatter.cs

#
C# | 46 lines | 38 code | 5 blank | 3 comment | 1 complexity | c7778811be327801fe9f4b334b2340d7 MD5 | raw file
 1// <copyright>
 2//   Copyright (c) Microsoft Corporation.  All rights reserved.
 3// </copyright>
 4
 5namespace Microsoft.ApplicationServer.Http
 6{
 7    using System;
 8    using System.Collections.Generic;
 9    using System.IO;
10    using System.Linq;
11    using System.Net;
12    using System.Net.Http.Formatting;
13    using System.Net.Http.Headers;
14
15    public class JsonpMediaTypeFormatter : JsonMediaTypeFormatter
16    {
17        public JsonpMediaTypeFormatter()
18        {
19            MediaTypeHeaderValue jsonpMediaType = new MediaTypeHeaderValue("application/javascript");
20
21            SupportedMediaTypes.Add(jsonpMediaType);
22            SupportedMediaTypes.Add(new MediaTypeHeaderValue("text/javascript"));
23
24            MediaTypeMappings.Add(new UriPathExtensionMapping("jsonp", jsonpMediaType));
25        }
26
27        protected override void OnWriteToStream(Type type, object value, Stream stream, HttpContentHeaders contentHeaders, TransportContext context)
28        {
29            IEnumerable<string> callbackValues = null;
30            if (contentHeaders.TryGetValues("jsonp-callback", out callbackValues))
31            {
32                var callback = callbackValues.First<string>();
33                var writer = new StreamWriter(stream);
34                writer.Write(callback + "(");
35                writer.Flush();
36                base.OnWriteToStream(type, value, stream, contentHeaders, context);
37                writer.Write(")");
38                writer.Flush();
39            }
40            else
41            {
42                base.OnWriteToStream(type, value, stream, contentHeaders, context);
43            }
44        }
45    }
46}