Created
January 21, 2012 03:20
-
-
Save darrelmiller/1651087 to your computer and use it in GitHub Desktop.
Simple Object Content
This file contains hidden or 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 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; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
This looks good to me. I am assuming this would still require the formatter methods to be public?