Skip to content

Instantly share code, notes, and snippets.

@panesofglass
Forked from darrelmiller/SimpleObjectContent.cs
Created January 21, 2012 03:23
Show Gist options
  • Save panesofglass/1651094 to your computer and use it in GitHub Desktop.
Save panesofglass/1651094 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
Author

Why don't you pass the TransportContext through to formatter.WriteToStreamAsync?

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