当他访问我的网站时,我想使用 httpcookie 向客户端系统添加 3 个串行密钥
但
序列号不同不同不一样。
当我添加第 4 个 cookie 时,会自动删除 1 个密钥。
我怎么能做到这一点。
当用户想看时,他可以看到最近的 3 个键。
您知道如何通过 asp.net mvc 网站将此 cookie 添加到客户端系统吗?
我如何将 key1 、 key 2 、 key3 添加到客户端系统。
当他访问我的网站时,我想使用 httpcookie 向客户端系统添加 3 个串行密钥
但
序列号不同不同不一样。
当我添加第 4 个 cookie 时,会自动删除 1 个密钥。
我怎么能做到这一点。
当用户想看时,他可以看到最近的 3 个键。
您知道如何通过 asp.net mvc 网站将此 cookie 添加到客户端系统吗?
我如何将 key1 、 key 2 、 key3 添加到客户端系统。
这是你可以做到的。
编写序列号。
//create a cookie
HttpCookie SerialKeys = new HttpCookie("SerialKeys");
//Add serial-key-values in the cookie
SerialKeys.Values.Add("key1", "your-first-serialkey");
SerialKeys.Values.Add("key2", "your-second-serialkey");
SerialKeys.Values.Add("key3", "your-third-serialkey");
SerialKeys.Values.Add("key4", "your-fourth-serialkey");
//set cookie expiry date-time. Made it to last for next 12 hours.
SerialKeys.Expires = DateTime.Now.AddHours(12);
//Most important, write the cookie to client.
Response.Cookies.Add(SerialKeys);
读取序列号 cookie。
//Assuming user comes back after several hours. several < 12.
//Read the cookie from Request.
HttpCookie SerialKeys = Request.Cookies["SerialKeys"];
if (SerialKeys == null)
{
//No cookie found or cookie expired.
//Handle the situation here, Redirect the user or simply return;
}
//ok - cookie is found.
//Gracefully check if the cookie has the key-value as expected.
if (!string.IsNullOrEmpty(SerialKeys.Values["key1"]))
{
string serialKey = SerialKeys.Values["key1"].ToString();
//Yes key1 is found. Mission accomplished.
}
if (!string.IsNullOrEmpty(SerialKeys.Values["key2"]))
{
string serialKey = SerialKeys.Values["key2"].ToString();
//Yes key2 is found. Mission accomplished.
}
您可以在用户启动会话时向用户添加 cookie。这可以通过在应用程序的 global.asax 文件中处理会话开始来完成,并添加用于创建这些密钥的逻辑代码。
void Session_OnStart() {
HttpCookie key1 = new HttpCookie("key1","123");
Request.Cookies.Add(key1);
}
然后,对于您所说的第四个 cookie,您可以通过使用Response.Cookies["cookie"]
或删除一个使用来引用用户 cookie 来创建代码逻辑Request.Cookies.Remove("cookie");
所有浏览器都以一种或另一种方式限制某个网站可以存储的 cookie 数量。例如,如果您的浏览器接受 n 个 cookie,则当您发送 n+1 时,浏览器将删除您最旧的一个。在我看来,这就是正在发生的事情。
一种可能的解决方案是使用一个具有各种子值的 cookie 而不是一个。这样,您可以在一个 cookie 中包含任意数量的值(始终遵守 cookie 最大大小限制,即 4086 字节)。
执行此操作的代码类似于:
//This code creates the cookie, ads some subvalues to it and then adds it to the request so its sent to the browser
HttpCookie cookie = new HttpCookie();
cookie.Name = "MyKeys";
cookie.Values.Add("Key1", "ValueKey1");
cookie.Values.Add("Key2", "ValueKey2");
cookie.Values.Add("Key3", "ValueKey3");
//etc...
Request.Cookies.Add(cookie);
//This code reads the data from the cookie.
HttpCookie rcookie = Response.Cookies.Get("MyKeys");
string value1, value2, value3;
//We verify it the variable is null because the cookie might not exist in the users browser. If so, this variable would be null
if (rcookie != null)
{
value1 = rcookie.Values.Get("Key1");
value2 = rcookie.Values.Get("Key2");
value3 = rcookie.Values.Get("Key3");
}