在.net中覆盖cookie的问题
本文关键字:问题 cookie 覆盖 net | 更新日期: 2023-09-27 18:11:44
任何时候我试图检索这个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();
}
任何帮助在这是非常感激!!
当显式设置cookie的域名时,域名应该以前导点开始。尝试将域设置为.url.com
,看看是否有效。
来自RFC 2109:
Domain=domain
Optional. The Domain attribute specifies the domain for which the
cookie is valid. An explicitly specified domain must always start
with a dot.