1

我尝试通过 Socket 发送 HttpWebRequest,当我想对其进行序列化时,我得到了这个异常:

mscorlib.dll 中出现“System.Runtime.Serialization.SerializationException”类型的未处理异常附加信息:在程序集“系统”中键入“System.Net.WebRequest+WebProxyWrapper”,版本=4.0.0.0,文化=中性,PublicKeyToken=b77a5c561934e089 ' 未标记为可序列化。

这是我的代码:

 [Serializable()]

class BROWSER
{
    HttpListener Response = null;
    HttpListenerContext context = null;
    HttpListenerRequest request = null;
    HttpListenerResponse response = null;
    public HttpWebRequest Webrequest = null;
    public WebResponse Webresponce = null;
    string responseString = null; 
    //when my Webrequest is ready ...
      public void SendToProxyServer(HttpWebRequest Webrequest)
    {
        byte[] SndData;
        S_RSocket sock = new S_RSocket();
        SndData = Serializ.seryaliz(this.Webrequest);
        sock.Send(SndData);
        this.responseString = sock.res;

    }

和我的序列化类:

abstract class Serializ
 {
   #region Filds
   static MemoryStream ms = null;
   static BinaryFormatter formatter = null;
   #endregion
   #region Methods
   public static byte [] seryaliz(object obj)
   {
       ms = new MemoryStream();
       formatter = new BinaryFormatter();
       formatter.Serialize(ms, obj);
       ms.Position = 0;
       String tmp = null;
       StreamReader sr = new StreamReader(ms);
       tmp = sr.ReadToEnd();
       ms.Position = 0;
       sr.Close();
       ms.Close();
       return Encoding.ASCII.GetBytes(tmp);
   }
   public static object DEseryaliz(byte [] Data)
   {
       object obj = new object();
       formatter = new BinaryFormatter();
       ms = new MemoryStream(Data);
       ms.Position = 0;
       obj=(object)formatter.Deserialize(ms);
       ms.Close();
       return obj;

   }
   #endregion 
 }

我将我的类设置为 Serializable() 但它不起作用。

问题出在哪里?

4

2 回答 2

2

您无法序列化 HttpWebRequest,因为它或它具有的属性无法序列化,因为它们没有Serializable属性。在这种情况下,它是 HttpWebRequest 中的一个属性。添加Serializable到正在执行序列化的类不会做任何事情。

于 2015-02-03T22:39:04.160 回答
2

哪里有问题?

这个问题在异常中得到了完美的描述:

在程序集 'System, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089' 中键入 'System.Net.WebRequest+WebProxyWrapper' 未标记为可序列化。

仅仅因为您将某些东西标记为[Serializable()]并不意味着它实际上可以按照SerializableAttribute 备注

将 SerializableAttribute 属性应用于一个类型以指示该类型的实例可以被序列化。如果正在序列化的对象图中的任何类型未应用 SerializableAttribute 属性,则公共语言运行库将引发 SerializationException。

您的字段或属性之一正在使用WebRequest内部具有WebProxyWrapper未标记为可序列化的类。因此,您无法序列化您的 WebRequest,因为它的字段或属性之一正在使用WebProxyWrapper.

于 2015-02-03T22:39:52.577 回答