Skip to content

Instantly share code, notes, and snippets.

@aliostad
Created April 28, 2012 15:17
Show Gist options
  • Star 8 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save aliostad/2519771 to your computer and use it in GitHub Desktop.
Save aliostad/2519771 to your computer and use it in GitHub Desktop.
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;
}
}
Copy link

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

Copy link

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

@lexyfeito
Copy link

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

@LuisMiguelFilipe
Copy link

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