Create a gist now

Instantly share code, notes, and snippets.

An ASP.NET Web API media type formatter for application/octet-stream
public class BinaryMediaTypeFormatter : MediaTypeFormatter
{
private static Type _supportedType = typeof (byte[]);
private bool _isAsync = false;
public BinaryMediaTypeFormatter() : this(false)
{
}
public BinaryMediaTypeFormatter(bool isAsync)
{
SupportedMediaTypes.Add(new MediaTypeHeaderValue("application/octet-stream"));
IsAsync = isAsync;
}
public bool IsAsync
{
get { return _isAsync; }
set { _isAsync = value; }
}
public override bool CanReadType(Type type)
{
return type == _supportedType;
}
public override bool CanWriteType(Type type)
{
return type == _supportedType;
}
public override Task<object> ReadFromStreamAsync(Type type, Stream stream,
HttpContentHeaders contentHeaders, IFormatterLogger formatterLogger)
{
Task<object> readTask = GetReadTask(stream);
if(_isAsync)
{
readTask.Start();
}
else
{
readTask.RunSynchronously();
}
return readTask;
}
private Task<object> GetReadTask(Stream stream)
{
return new Task<object>(() =>
{
var ms = new MemoryStream();
stream.CopyTo(ms);
return ms.ToArray();
});
}
private Task GetWriteTask(Stream stream, byte[] data)
{
return new Task(() =>
{
var ms = new MemoryStream(data);
ms.CopyTo(stream);
});
}
public override Task WriteToStreamAsync(Type type, object value, Stream stream,
HttpContentHeaders contentHeaders, TransportContext transportContext)
{
if (value == null)
value = new byte[0];
Task writeTask = GetWriteTask(stream, (byte[]) value);
if(_isAsync)
{
writeTask.Start();
}
else
{
writeTask.RunSynchronously();
}
return writeTask;
}
}
@ghost
ghost commented May 21, 2014

Why does "ReadFromStreamAsync" and "WriteToStreamAsync" show errors on complie? It says it cannot be overriden.. Im using ASP.Net MVC 4.5

@ghost
ghost commented May 21, 2014

It works now, I just changed, HttpContentHeaders to HttpContent.
Code works now.. Your code is such a big big help.. Thank You!!!!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment