每当我尝试在他们通过我们的支付网关(重定向到不同的域,然后将用户带回我们的页面)后检索此 cookie 时,cookie 不会持续存在:(
它的行为就像它根本没有从 cookie 中加载对象一样。
这是我用来存储/恢复 cookie 的代码:
public static string Store(EIN ein)
{
HttpCookie cookie = new HttpCookie("test123")
{
// Set the expiry date of the cookie to 15 years
Expires = DateTime.Now.AddYears(15)
};
Stream myStream = new MemoryStream();
try
{
// Create a binary formatter and serialize the
// myClass into the memorystream
IFormatter formatter = new BinaryFormatter();
formatter.Serialize(myStream, ein);
// Go to the beginning of the stream and
// fill a byte array with the contents of the
// memory stream
myStream.Seek(0, SeekOrigin.Begin);
byte[] buffer = new byte[myStream.Length];
myStream.Read(buffer, 0, (int)myStream.Length);
// Store the buffer as a base64 string in the cookie
cookie.Value = Convert.ToBase64String(buffer);
cookie.Domain = "url.com";
// Add the cookie to the current http context
HttpContext.Current.Response.Cookies.Add(cookie);
}
finally
{
// ... and remember to close the stream
myStream.Close();
}
return cookie.Path;
}
public static EIN Restore()
{
// Always remember to check that the cookie is not empty
HttpCookie cookie = HttpContext.Current.Request.Cookies["test123"];
if (cookie != null)
{
// Convert the base64 string into a byte array
byte[] buffer = Convert.FromBase64String(cookie.Value);
// Create a memory stream from the byte array
Stream myStream = new MemoryStream(buffer);
try
{
// Create a binary formatter and deserialize the
// contents of the memory stream into MyClass
IFormatter formatter = new BinaryFormatter();
EIN streamedClass = (EIN)formatter.Deserialize(myStream);
return streamedClass;
}
finally
{
// ... and as always, close the stream
myStream.Close();
}
}
return new EIN();
}
非常感谢您对此的任何帮助!