Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
public interface IHttpMessageSerializer
{
void Serialize(HttpResponseMessage response, Stream stream);
void Serialize(HttpRequestMessage request, Stream stream);
HttpResponseMessage DeserializeToResponse(Stream stream);
HttpRequestMessage DeserializeToRequest(Stream stream);
}
public class MessageContentHttpMessageSerializer : IHttpMessageSerializer
{
private bool _bufferContent;
public MessageContentHttpMessageSerializer() : this(false)
{
}
public MessageContentHttpMessageSerializer(bool bufferContent)
{
_bufferContent = bufferContent;
}
public void Serialize(HttpResponseMessage response, Stream stream)
{
byte[] assuranceBuffer = null;
if (_bufferContent && response.Content != null)
assuranceBuffer = response.Content.ReadAsByteArrayAsync().Result; // make sure it is buffered
var httpMessageContent = new HttpMessageContent(response);
var buffer = httpMessageContent.ReadAsByteArrayAsync().Result;
stream.Write(buffer, 0, buffer.Length);
}
public void Serialize(HttpRequestMessage request, Stream stream)
{
byte[] assuranceBuffer = null;
if (_bufferContent && request.Content != null)
assuranceBuffer = request.Content.ReadAsByteArrayAsync().Result; // make sure it is buffered
var httpMessageContent = new HttpMessageContent(request);
var buffer = httpMessageContent.ReadAsByteArrayAsync().Result;
stream.Write(buffer, 0, buffer.Length);
}
public HttpResponseMessage DeserializeToResponse(Stream stream)
{
var response = new HttpResponseMessage();
var memoryStream = new MemoryStream();
stream.CopyTo(memoryStream);
response.Content = new ByteArrayContent(memoryStream.ToArray());
response.Content.Headers.Add("Content-Type", "application/http;msgtype=response");
return response.Content.ReadAsHttpResponseMessageAsync().Result;
}
public HttpRequestMessage DeserializeToRequest(Stream stream)
{
var request = new HttpRequestMessage();
var memoryStream = new MemoryStream();
stream.CopyTo(memoryStream);
request.Content = new ByteArrayContent(memoryStream.ToArray());
request.Content.Headers.Add("Content-Type", "application/http;msgtype=request");
return request.Content.ReadAsHttpRequestMessageAsync().Result;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment