为了记录一些HTTP流量,我正在尝试序列化System.Net.HttpWebRequest的一个实例。该应用程序使用MVC 3,问题代码位于控制器类的操作方法中。
在.NET Framework 4中,类documented为可序列化:
[SerializableAttribute]
public class HttpWebRequest : WebRequest,
ISerializable
以下测试代码在指定的声明中失败:
...
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();
报告的错误是:
Type 'System.Net.WebRequest+WebProxyWrapper' in Assembly
'System, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089'
is not marked as serializable.
我试过追逐WebProxyWrapper没有任何乐趣。只是一点无益的包袱。将HttpWebRequest显式地转换为WebRequest不会改变错误:
formatter.Serialize(msRequest, (WebRequest)preapprovalRequest);
从好的方面来说,代码可以正确地序列化和反序列化HttpWebResponse的实例。
如何丢失包装?有更好的方法吗?
答案 0 :(得分:0)
试一试:
[Serializable()]
public class MyClass
{
//your serializable class
}
答案 1 :(得分:0)
微软的官方回答:
感谢您的反馈。不幸的是HttpWebRequest下降了 支持.NET 1.1之后的序列化。看到 http://msdn.microsoft.com/en-us/library/system.net.httpwebrequest.httpwebrequest(v=VS.100).aspx
我们将看看是否可以删除该属性以避免这种混淆 在将来。
他们更改了文档以包含[ObsoleteAttribute]属性。