For more direct control over the payload you are passing, you can create HttpContent derived classes instead of passing your object to the ObjectContent class, which then passes the streams to the Formatter class.
The JsonContent class, which supports reading and writing, looks like this:
public class JsonContent : HttpContent { private readonly Stream _inboundStream; private readonly JToken _value; public JsonContent(JToken value) { _value = value; Headers.ContentType = new MediaTypeHeaderValue("application/json"); } public JsonContent(Stream inboundStream) { _inboundStream = inboundStream; } public async Task<JToken> ReadAsJTokenAsync() { return _value ?? JToken.Parse(await ReadAsStringAsync()); } protected async override Task<Stream> CreateContentReadStreamAsync() { return _inboundStream; } protected override Task SerializeToStreamAsync(Stream stream, TransportContext context) { if (_value != null) { var jw = new JsonTextWriter(new StreamWriter(stream)) {Formatting = Formatting.Indented}; _value.WriteTo(jw); jw.Flush(); } else if (_inboundStream != null) { return _inboundStream.CopyToAsync(stream); } return Task.FromResult<object>(null); } protected override bool TryComputeLength(out long length) { length = -1; return false; } protected override void Dispose(bool disposing) { if (disposing) { _inboundStream.Dispose(); } base.Dispose(disposing); } }
Once you get this class,
var content = new JsonContent(myObject); _httpClient.PostAsync(uri,content);
If you need to change the content title, you can do it manually before submitting a request. And if you need to bother with any request header, you use SendAsync overload,
var content = new JsonContent(myObject); // Update Content headers here var request = new HttpRequestMessage {RequestUri = uri, Content = content }; // Update request headers here _httpClient.SendAsync(request);
Derived content classes are easy to create for almost any type of medium or any data source. I created all the classes derived from HttpContent. e.g. FileContent, EmbeddedResourceContent, CSVContent, XmlContent, ImageContent, HalContent, CollectionJsonContent, HomeContent, ProblemContent.
Personally, I have found that this gives me much better control over my payloads.
Darrel miller
source share