During Asp.net development, the longest value passing between pages is for explicitly passing parameters, sessions, applications, and cookie values through URLs. If you do not consider the impact of performance on page transfer of complex objects, you can usually use session or application. So how can we pass complex objects between pages through URLs? As the title says, the object --> string, and then the string --> object. In this process, you can use the following
Code To achieve:
Code
Using System;
Using System. runtime. serialization;
Using System. runtime. serialization. formatters. Binary;
Using System. IO;
NamespaceDOTNET. Common. Utilities
{
Public ClassSerializeobj
{
PublicSerializeobj ()
{}
/// <Summary>
/// Serialize an object to a string
/// </Summary>
/// <Param name = "OBJ"> Generic object </Param>
/// <Returns> Serialized string </Returns>
Public Static String Serialize < T > (T obj)
{
Try
{
Iformatter formatter = New Binaryformatter ();
Memorystream stream = New Memorystream ();
Formatter. serialize (stream, OBJ );
Stream. Position = 0 ;
Byte [] Buffer = New Byte [Stream. Length];
Stream. Read (buffer, 0 , Buffer. Length );
Stream. Flush ();
Stream. Close ();
Return Convert. tobase64string (buffer );
}
Catch (Exception ex)
{
Throw New Exception ( " Serialization failed due: " + Ex. Message );
}
}
/// <Summary>
/// Deserializing a string to an object
/// </Summary>
/// <Param name = "OBJ"> Generic object </Param>
/// <Param name = "str"> String to be converted to an object </Param>
/// <Returns> Deserialized object </Returns>
Public Static T desrialize < T > (T obj, String Str)
{
Try
{
OBJ = Default (T );
Iformatter formatter = New Binaryformatter ();
Byte [] Buffer = Convert. frombase64string (STR );
Memorystream stream = New Memorystream (buffer );
OBJ = (T) formatter. deserialize (Stream );
Stream. Flush ();
Stream. Close ();
}
Catch (Exception ex)
{
Throw New Exception ( " Deserialization failed. cause: " + Ex. Message );
}
Return OBJ;
}
}
}
It should be noted that the total length of parameters is limited through URL transmission parameters (get mode) (for too long parameters, users who do not know the technology have psychological barriers ). If the length of a complex object after being serialized as a string exceeds the limit of the get method, the value passing of this object is not suitable for explicit URL transfer, you can select other methods, such as post or session.