In order to log some HTTP traffic I'm trying to serialize an instance of System.Net.HttpWebRequest. The application uses MVC 3 and the problem code is in an action method in a controller class.
In .NET Framework 4 it the class is documented as serializable:
[SerializableAttribute]
public class HttpWebRequest : WebRequest,
ISerializable
The following test code fails at the indicated statement:
...
HttpWebRequest preapprovalRequest = (HttpWebRequest)WebRequest.Create("http://big.URL.here");
...
HttpWebResponse preapprovalResponse = (HttpWebResponse)preapprovalRequest.GetResponse();
// Serialize the request context.
IFormatter formatter = new BinaryFormatter();
MemoryStream msRequest = new MemoryStream();
formatter.Serialize(msRequest, preapprovalRequest); //<<<<< Error here.
// Reset the stream and deserialize.
msRequest.Seek(0, SeekOrigin.Begin);
HttpWebRequest duplicateRequest = (HttpWebRequest)formatter.Deserialize(msRequest);
msRequest.Close();
// Serialize the response context.
MemoryStream msResponse = new MemoryStream();
formatter.Serialize(msResponse, preapprovalResponse);
// Reset the stream and deserialize.
msResponse.Seek(0, SeekOrigin.Begin);
HttpWebResponse duplicateResponse = (HttpWebResponse)formatter.Deserialize(msResponse);
msResponse.Close();
The error reported is:
Type 'System.Net.WebRequest+WebProxyWrapper' in Assembly
'System, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089'
is not marked as serializable.
I've tried chasing WebProxyWrapper with no joy. Just a bit of unhelpful baggage. Explicitly casting the HttpWebRequest to a WebRequest doesn't alter the error:
formatter.Serialize(msRequest, (WebRequest)preapprovalRequest);
On the bright side, the code does properly serialize and deserialize the instance of HttpWebResponse.
How can I lose the wrapper? Is there a better approach?