在我们的asp.net应用程序中,我们正在实现内存缓存技术。为此,我们将对象序列化格式的类存储并与密钥一起存储到内存缓存服务器中。
检索时,我们使用key并检索数据,然后反序列化返回实际类。
该错误未在本地计算机中发生,而是在罕见的scnairo中的服务器中发生。
反序列化时,我们遇到以下错误,
Exception:Binary stream '111' does not contain a valid BinaryHeader. Possible causes are invalid stream or object version change between serialization and deserialization.
Stack Trace:System.Runtime.Serialization.SerializationException: Binary stream '111' does not contain a valid BinaryHeader. Possible causes are invalid stream or object version change between serialization and deserialization.
at System.Runtime.Serialization.Formatters.Binary.__BinaryParser.Run()
at System.Runtime.Serialization.Formatters.Binary.ObjectReader.Deserialize(HeaderHandler handler, __BinaryParser serParser, Boolean fCheck, Boolean isCrossAppDomain, IMethodCallMessage methodCallMessage)
at System.Runtime.Serialization.Formatters.Binary.BinaryFormatter.Deserialize(Stream serializationStream, HeaderHandler handler, Boolean fCheck, Boolean isCrossAppDomain, IMethodCallMessage methodCallMessage)
at System.Runtime.Serialization.Formatters.Binary.BinaryFormatter.Deserialize(Stream serializationStream)
at TUtil.DeserializeFromStream(MemoryStream stream)
我们在应用程序中使用的以下用于序列化和反序列化的代码。
public static MemoryStream SerializeToStream(object o)
{
try
{
MemoryStream stream = new MemoryStream();
IFormatter formatter = new System.Runtime.Serialization.Formatters.Binary.BinaryFormatter();
formatter.Serialize(stream, o);
return stream;
}
catch (Exception)
{
throw;
}
}
public static object DeserializeFromStream(MemoryStream stream)
{
try
{
IFormatter formatter = new System.Runtime.Serialization.Formatters.Binary.BinaryFormatter();
stream.Position = 0;
stream.Seek(0, SeekOrigin.Begin);
object o = formatter.Deserialize(stream);
return o;
}
catch (Exception)
{
throw;
}
}
上面的序列化和反序列化的调用功能,
public static T FetchCache<T>(string Keyname)
{
try
{
mStr = (MemoryStream)mCache.Get(Keyname);
if (mStr != null)
{
return (T)TUtil.DeserializeFromStream(mStr);
}
else { return default(T); }
}
catch
{
throw;
}
}
public static bool StoreCache<T>(string Keyname, T Obj, DateTime expirelimit)
{
try
{
mStr = TUtil.SerializeToStream(Obj);
return mCache.Store(StoreMode.Set, Keyname, mStr, expirelimit);
}
catch (Exception exp)
{
Log.WriteError("StoreCache<T>(): {0}", exp);
return false;
}
}