jellyfin/MediaBrowser.Common/Net/Handlers/BaseJsonHandler.cs

47 lines
1.3 KiB
C#
Raw Normal View History

using System.IO;
using System.Threading.Tasks;
using MediaBrowser.Common.Serialization;
namespace MediaBrowser.Common.Net.Handlers
{
public abstract class BaseJsonHandler<T> : BaseHandler
{
public override Task<string> GetContentType()
{
2012-08-22 02:50:59 +00:00
return Task.FromResult<string>(MimeTypes.JsonMimeType);
}
private bool _ObjectToSerializeEnsured = false;
private T _ObjectToSerialize;
private async Task EnsureObjectToSerialize()
{
if (!_ObjectToSerializeEnsured)
{
2012-08-22 02:50:59 +00:00
_ObjectToSerialize = await GetObjectToSerialize().ConfigureAwait(false);
if (_ObjectToSerialize == null)
{
StatusCode = 404;
}
_ObjectToSerializeEnsured = true;
}
}
protected abstract Task<T> GetObjectToSerialize();
2012-08-22 02:50:59 +00:00
protected override Task PrepareResponse()
{
2012-08-22 02:50:59 +00:00
return EnsureObjectToSerialize();
}
protected async override Task WriteResponseToOutputStream(Stream stream)
{
await EnsureObjectToSerialize();
JsonSerializer.SerializeToStream<T>(_ObjectToSerialize, stream);
}
}
}