当他访问我们的网站时,如何将串行密钥添加到客户系统中
-
02-10-2019 - |
题
我想使用HTTPCookie访问我的网站时,我想在客户端系统中添加3个串行密钥
但
串行键不同不同。
当我添加第四个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);
阅读串行键曲奇。
//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,您可以通过使用使用用户cookie来创建代码逻辑 Response.Cookies["cookie"]
或使用一个使用 Request.Cookies.Remove("cookie");
所有浏览器以一种或另一种方式限制某个网站可以存储的cookie量。例如,如果您的浏览器接受N cookie,则当您发送n+1时,浏览器将删除最旧的cookie。在我看来,这就是正在发生的事情。
一种可能的解决方案是将一个带有各种子视价的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");
}
不隶属于 StackOverflow