Created
April 28, 2012 15:17
-
-
Save aliostad/2519771 to your computer and use it in GitHub Desktop.
An ASP.NET Web API media type formatter for application/octet-stream
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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; | |
} | |
} |
It works now, I just changed, HttpContentHeaders to HttpContent.
Code works now.. Your code is such a big big help.. Thank You!!!!
Hi, can you tell me how i would i use this?
Hi, can you tell me how i would i use this?
https://docs.microsoft.com/en-us/aspnet/web-api/overview/formats-and-model-binding/media-formatters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Why does "ReadFromStreamAsync" and "WriteToStreamAsync" show errors on complie? It says it cannot be overriden.. Im using ASP.Net MVC 4.5