BaseSerializationHandler.cs 2.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394
  1. using System;
  2. using System.IO;
  3. using System.Threading.Tasks;
  4. using MediaBrowser.Common.Serialization;
  5. namespace MediaBrowser.Common.Net.Handlers
  6. {
  7. public abstract class BaseJsonHandler<T> : BaseHandler
  8. {
  9. public SerializationFormat SerializationFormat
  10. {
  11. get
  12. {
  13. string format = QueryString["dataformat"];
  14. if (string.IsNullOrEmpty(format))
  15. {
  16. return Handlers.SerializationFormat.Json;
  17. }
  18. return (SerializationFormat)Enum.Parse(typeof(SerializationFormat), format, true);
  19. }
  20. }
  21. public override Task<string> GetContentType()
  22. {
  23. switch (SerializationFormat)
  24. {
  25. case Handlers.SerializationFormat.Jsv:
  26. return Task.FromResult<string>("text/plain");
  27. case Handlers.SerializationFormat.Protobuf:
  28. return Task.FromResult<string>("application/x-protobuf");
  29. default:
  30. return Task.FromResult<string>(MimeTypes.JsonMimeType);
  31. }
  32. }
  33. private bool _ObjectToSerializeEnsured = false;
  34. private T _ObjectToSerialize;
  35. private async Task EnsureObjectToSerialize()
  36. {
  37. if (!_ObjectToSerializeEnsured)
  38. {
  39. _ObjectToSerialize = await GetObjectToSerialize().ConfigureAwait(false);
  40. if (_ObjectToSerialize == null)
  41. {
  42. StatusCode = 404;
  43. }
  44. _ObjectToSerializeEnsured = true;
  45. }
  46. }
  47. protected abstract Task<T> GetObjectToSerialize();
  48. protected override Task PrepareResponse()
  49. {
  50. return EnsureObjectToSerialize();
  51. }
  52. protected async override Task WriteResponseToOutputStream(Stream stream)
  53. {
  54. await EnsureObjectToSerialize();
  55. switch (SerializationFormat)
  56. {
  57. case Handlers.SerializationFormat.Jsv:
  58. JsvSerializer.SerializeToStream<T>(_ObjectToSerialize, stream);
  59. break;
  60. case Handlers.SerializationFormat.Protobuf:
  61. ProtobufSerializer.SerializeToStream<T>(_ObjectToSerialize, stream);
  62. break;
  63. default:
  64. JsonSerializer.SerializeToStream<T>(_ObjectToSerialize, stream);
  65. break;
  66. }
  67. }
  68. public override bool ShouldCompressResponse(string contentType)
  69. {
  70. return SerializationFormat != Handlers.SerializationFormat.Protobuf;
  71. }
  72. }
  73. public enum SerializationFormat
  74. {
  75. Json,
  76. Jsv,
  77. Protobuf
  78. }
  79. }