PageRenderTime 44ms CodeModel.GetById 17ms RepoModel.GetById 0ms 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
Possible License(s): CC-BY-SA-3.0, Apache-2.0
  1. // <copyright>
  2. // Copyright (c) Microsoft Corporation. All rights reserved.
  3. // </copyright>
  4. namespace Microsoft.ApplicationServer.Http
  5. {
  6. using System;
  7. using System.Collections.Generic;
  8. using System.IO;
  9. using System.Linq;
  10. using System.Net;
  11. using System.Net.Http.Formatting;
  12. using System.Net.Http.Headers;
  13. public class JsonpMediaTypeFormatter : JsonMediaTypeFormatter
  14. {
  15. public JsonpMediaTypeFormatter()
  16. {
  17. MediaTypeHeaderValue jsonpMediaType = new MediaTypeHeaderValue("application/javascript");
  18. SupportedMediaTypes.Add(jsonpMediaType);
  19. SupportedMediaTypes.Add(new MediaTypeHeaderValue("text/javascript"));
  20. MediaTypeMappings.Add(new UriPathExtensionMapping("jsonp", jsonpMediaType));
  21. }
  22. protected override void OnWriteToStream(Type type, object value, Stream stream, HttpContentHeaders contentHeaders, TransportContext context)
  23. {
  24. IEnumerable<string> callbackValues = null;
  25. if (contentHeaders.TryGetValues("jsonp-callback", out callbackValues))
  26. {
  27. var callback = callbackValues.First<string>();
  28. var writer = new StreamWriter(stream);
  29. writer.Write(callback + "(");
  30. writer.Flush();
  31. base.OnWriteToStream(type, value, stream, contentHeaders, context);
  32. writer.Write(")");
  33. writer.Flush();
  34. }
  35. else
  36. {
  37. base.OnWriteToStream(type, value, stream, contentHeaders, context);
  38. }
  39. }
  40. }
  41. }