Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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

This comment has been minimized.

Copy link

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

This comment has been minimized.

Copy link

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!!!!

@lexyfeito

This comment has been minimized.

Copy link

commented Oct 24, 2017

Hi, can you tell me how i would i use this?

@LuisMiguelFilipe

This comment has been minimized.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.