Make Headers serializable

Topics: Web Api
Jan 6, 2012 at 2:24 PM

I would like headers (both request and response) be serializable.

On the client side, request headers can be reused multiple times by deserializing the ones that were last used from the user.

On the server side, response headers can be reused depending on the server state.

Am I missing a shortcut to serialize/deserialize them?
Is there any other particular reason for not having marked them as serializable?


Jan 11, 2012 at 3:54 PM

By serialization and deserialization you mean that you want an efficient way to bulk copy headers, correct?  On the client side, how is this different from using HttpClient.DefaultRequestHeaders?

Jan 11, 2012 at 3:59 PM

I need to read/write them on a file. So 'serialize/deserialize' sounds more correct.
In my scenario I have different sets of headers for different requests. I want to use these sets of headers as 'templates'.

I also need to visualize them for advanced users and this is requiring a lot of work to create the WPF controls to edit/modify them. (But this is another story).


Jan 12, 2012 at 11:01 PM

You can encapsulate an HttpRequestMessage or HttpResponseMessage using an HttpMessageContent which derives from HttpContent. That allows you to serialize an HttpRequestMessage or HttpResponseMessage to a stream and to deserialize it from a stream and recreate an HttpRequestMessage or HttpResponseMessage. HttpMessageContent is a full HttpContent so you can include it wherever HttpContent can be included -- for example as an HTTP request entity body. 

Three small code snippets illustrate creation of HttpMessageContent, serialization to stream, and deserialization from stream respectively:

  HttpResponseMessage httpResponse = new HttpResponseMessage();
  HttpMessageContent httpMessageContent = new HttpMessageContent(httpResponse);

  MemoryStream output = new MemoryStream();
  output.Position = 0;

  StreamContent input = new StreamContent(output);

The mediatype for HTTP requests and responses is defined by the HTTP spec as "application/http; type=request" and "application/http; type=response" respectively.

Hope this helps,