我正在尝试将一个对象从我的 ASP .NET C# MVC3 项目发送到同一解决方案中的 Silverlight 项目。
这是我用来序列化和反序列化的代码,我从 CodeProject (http://www.codeproject.com/Articles/233914/Passing-Objects-between-ASP-NET-and-Silverlight-Co) 获得的
public string getSerializedGameData()
{
Game g = Game.populateByID(this.gameID);
MemoryStream mem = new MemoryStream();
XmlSerializer xs = new XmlSerializer(typeof(Game));
mem.Seek(0, SeekOrigin.Begin);
xs.Serialize(mem, g);
byte[] data = mem.GetBuffer();
return Encoding.UTF8.GetString(data, 0, data.Length);
}
public static Game GetDeserializedGameObject(string xmlData)
{
StringReader sr = new StringReader(xmlData);
XmlSerializer xs = new XmlSerializer(typeof(Game));
return (Game)xs.Deserialize(sr);
}
这就是似乎有效的序列化和反序列化。
在我的 ASPX 页面中,我放了:
<input type="hidden" id="game" value="<%=HttpUtility.HtmlEncode(Game.populateByID(Convert.ToInt32(Request["gameID"])).getSerializedGameData()) %>" />
它应该获取对象,将其构建为字符串,并将其编码为 HTML。然后将其嵌入为隐藏字段。
要解码它,我正在使用:
string s = HttpUtility.HtmlDecode(HtmlPage.Document.GetElementById("game").GetProperty("value").ToString());
Game g = Game.GetDeserializedGameObject(s);
现在,当我运行时,我得到了错误:
Data at the root level is invalid. Line 443, position 8
查看数据,我看到有效的 XML,直到...
...
</gameEvents>
</Game>�����������
除了有数千个无效字符外,我删除了它们以保持简短。
看看我看到的来源:
...
</gameEvents>
</Game>" />
因此,这似乎不是编码问题。
最初我认为数据缓冲区中多余的字符,但我没有看到它在源代码中出现,如果 XML Serialize 和 Deseriailize 已经过测试,那就留下 HTMLDecode ..但我什么都找不到错了。
我意识到我可能会在最后一个 > 之后剥离所有内容,但我想知道是什么原因造成的,因为我不应该这样做。
任何帮助将不胜感激,谢谢!