Skip to content

Instantly share code, notes, and snippets.

@darrelmiller
Created January 21, 2012 03:20
Show Gist options
  • Save darrelmiller/1651087 to your computer and use it in GitHub Desktop.
Save darrelmiller/1651087 to your computer and use it in GitHub Desktop.
Simple Object Content
public class SimpleObjectContent<T> : HttpContent
{
private readonly T _outboundInstance;
private readonly HttpContent _inboundContent;
private readonly MediaTypeFormatter _formatter;
// Outbound constructor
public SimpleObjectContent(T outboundInstance, MediaTypeFormatter formatter)
{
_outboundInstance = outboundInstance;
_formatter = formatter;
}
//Inbound constructor
public SimpleObjectContent(HttpContent inboundContent, MediaTypeFormatter formatter)
{
_inboundContent = inboundContent;
_formatter = formatter;
}
protected override Task SerializeToStreamAsync(Stream stream, TransportContext context)
{
// FormatterContext is required by XmlMediaTypeFormatter, but is not used by WriteToStreamAsync of XmlMediaTypeFormatter!
return _formatter.WriteToStreamAsync(typeof (T), _outboundInstance, stream, this.Headers, new FormatterContext(new MediaTypeHeaderValue("application/bogus"), false), null);
}
public Task<T> ReadAsync()
{
return this.ReadAsStreamAsync()
.ContinueWith<object>(streamTask => _formatter.ReadFromStreamAsync(typeof(T), streamTask.Result, _inboundContent.Headers, new FormatterContext(new MediaTypeHeaderValue("application/bogus"), false)))
.ContinueWith<T>(objectTask => (T)((Task<object>)(objectTask.Result)).Result);
}
protected override Task<Stream> CreateContentReadStreamAsync()
{
return _inboundContent.ReadAsStreamAsync();
}
protected override bool TryComputeLength(out long length)
{
length =-1L;
return false;
}
}
@panesofglass
Copy link

This looks good to me. I am assuming this would still require the formatter methods to be public?

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