【翻译】使用ASP.NET序列化对象,基于http协议

原文链接:HTTP Binary Serialization through ASP.NET without WCF

      使用ASP.NET序列化对象,基于http协议

介绍

当开发c/s应用程序的时候,经常需要将一个对象发送个客户端。我们程序开发者处理这个对象的最简单的方法是获取整个对象,而不是一些属性。

         一种方法是使用WCF或者是WebService,这种方法本身能提供一整套的工具,比如通过对象序列化完成这个工作。如果你在项目里面想做的只是发送和获取一个或更多的对象,那这些技术对于自己的开发就是“大炮打麻雀”过于复杂了。

         对于这个让人困惑的问题,我花了些时间寻找解决问题的方法;我的目标是找到一种简单、方便而且不复杂的方法以实现在服务端创建一个对象,序列化,然后发送个客户端。在这安全和互通性不是问题的重点,所以我们可以先不考虑这些问题。这个问题的约束是我们必须保证方法的运行效率而且是基HTTP协议上的。

         我的解决方案是通过Asp.Net页面获取不同的查询字符串决定返回什么对象,创建对象,以二进制序列化它,并且以二进制的“附件”形式传到客户端。客户端通过WebClient类下载这个“附件”,并把“附件”反序列化成对象。

         服务端和客户端共享一个包含通用对象的类库。最初,我用XML序列化对象,但发现这种方式很慢。如果你需要考虑通用性还是可以用XML序列化的。

背景

         想着用WCF或WebService不是唯一的方法;当然你也可以用WCF的自定义绑定或用MTOM,但是据我个人经验那些方法对于简单的项目太过复杂了。

代码展示

         在页面加载的时候,我用代码去判断哪个对象客户端需要,并返回一个以二进制序列化后的对象“附件”。

 

代码
protected void Page_Load(objectsender, EventArgs e)
{
// Check whichobject the client wants
if(Request.QueryString["op"] == "getdata")
{
// Createa new instance of the sample data object
var data = newSampleData();
data.moreData
= 34343;
data.otherData
= true;
data.SomeData
= "fewoifjweofjwepo";
// Setcontent type and header
//octet-stream allow us to send binary data
// thefile name here is irrelevant as it is
// notactually used by the client.
Response.ContentType = "application/octet-stream";
Response.AppendHeader(
"Content-Disposition",
"attachment; filename=sampleData.bin");
//Serialzie the object and write it to the response stream
var binaryFormatter = new BinaryFormatter();
binaryFormatter.Serialize(Response.OutputStream, data);
// Itsimportant to end the response, overwise the other page content
// wouldbe sent to the client.
Response.End();
}

 

 

 

在客户端,我们通过使用查询字符串发送请求,然后反序列化服务端的回复。

 

 

代码
// Create the url for the service, this could be stored in a configurationfile
string url = "http://localhost/BinaryServiceSample/Default.aspx?op=getdata";
// Download the data to a byte array
// This data contains the actual object
varclient = new WebClient();
byte[] result= client.DownloadData(url);
// Create a memory stream to stored the object
var mem =new MemoryStream(result);
varbinaryFormatter
= new BinaryFormatter();
var data
= (SampleData)binaryFormatter.Deserialize(mem);
mem.Close();
// Write object to the console
Console.Write(data.ToString());
Console.ReadLine();
Pointsof Interest

 


 

 

  • l  尽管感觉二进制序列化可能用的“更舒服”,但在不同的平台上使用也许会不兼容。
  • l  用二进制序列化对象比使用XML序列化对象更快
  • l  以上代码不存在未解决的错误,而且可以很容易的使用它。我没有改善程序让它更简单更清楚。
  • l  也可以在发送序列化对象之前对字节进行加密,当然这使得想让它通用就更难了。
  • l  通过这种方式序列化一个对象让我在写程序的时候跟灵活,而其不会增加应用的复杂度。
posted @ 2009-12-19 13:08  吕飞  阅读(374)  评论(0)    收藏  举报