using MediaBrowser.Common.Extensions; using MediaBrowser.Common.Kernel; using System; using System.IO; using System.Threading.Tasks; namespace MediaBrowser.Common.Net.Handlers { /// /// Class BaseSerializationHandler /// /// The type of the T kernel type. /// public abstract class BaseSerializationHandler : BaseHandler where TKernelType : IKernel where T : class { /// /// Gets the serialization format. /// /// The serialization format. public SerializationFormat SerializationFormat { get { var format = QueryString["dataformat"]; if (string.IsNullOrEmpty(format)) { return SerializationFormat.Json; } return (SerializationFormat)Enum.Parse(typeof(SerializationFormat), format, true); } } /// /// Gets the type of the content. /// /// The type of the content. protected string ContentType { get { switch (SerializationFormat) { case SerializationFormat.Protobuf: return "application/x-protobuf"; default: return MimeTypes.JsonMimeType; } } } /// /// Gets the response info. /// /// Task{ResponseInfo}. protected override Task GetResponseInfo() { return Task.FromResult(new ResponseInfo { ContentType = ContentType }); } /// /// Called when [processing request]. /// /// The response info. /// Task. protected override async Task OnProcessingRequest(ResponseInfo responseInfo) { _objectToSerialize = await GetObjectToSerialize().ConfigureAwait(false); if (_objectToSerialize == null) { throw new ResourceNotFoundException(); } await base.OnProcessingRequest(responseInfo).ConfigureAwait(false); } /// /// The _object to serialize /// private T _objectToSerialize; /// /// Gets the object to serialize. /// /// Task{`0}. protected abstract Task GetObjectToSerialize(); /// /// Writes the response to output stream. /// /// The stream. /// The response info. /// Length of the content. /// Task. protected override Task WriteResponseToOutputStream(Stream stream, ResponseInfo responseInfo, long? contentLength) { return Task.Run(() => { //switch (SerializationFormat) //{ // case SerializationFormat.Protobuf: // Kernel.ProtobufSerializer.SerializeToStream(_objectToSerialize, stream); // break; // default: // JsonSerializer.SerializeToStream(_objectToSerialize, stream); // break; //} }); } } /// /// Enum SerializationFormat /// public enum SerializationFormat { /// /// The json /// Json, /// /// The protobuf /// Protobuf } }