我在stackoverflow上看到了ASP.NET MVC C#中的持久性cookie示例。 但我无法弄清楚为什么下面的代码不起作用。
首先我写信给cookie:
HttpCookie cookie = new HttpCookie("AdminPrintModule");
cookie.Expires = DateTime.Now.AddMonths(36);
cookie.Values.Add("PrinterSetting1", Request.QueryString["Printer1"]);
cookie.Values.Add("PrinterSetting2", Request.QueryString["Printer2"]);
cookie.Values.Add("PrinterSetting3", Request.QueryString["Printer3"]);
Response.Cookies.Add(cookie);
我看到存储在Internet Explorer中的cookie。内容看起来还不错。
然后阅读代码:
HttpCookie cookie = Request.Cookies["AdminPrintModule"];
test = cookie.Values["PrinterSetting2"].ToString();
cookie变量保持为null。将PrinterSetting2值存储在测试变量中失败。
我不知道我做错了什么,因为这或多或少是来自stackoverflow上示例的复制粘贴。为什么我不能从cookie中读取PrinterSetting2值?
答案 0 :(得分:1)
尝试以下代码: -
if (Request.Cookies["AdminPrintModule"] != null)
{
HttpCookie cookie = Request.Cookies["AdminPrintModule"];
test = cookie["PrinterSetting2"].ToString();
}
查看此文档http://www.c-sharpcorner.com/uploadfile/annathurai/cookies-in-Asp-Net/: -
以下几种类型可以写入和读取cookie: -
非持久Cookie - Cookie已过期时间称为 非持久性Cookie
如何创建cookie?它真的很容易创建一个cookie Asp.Net在Response对象或HttpCookie的帮助下
示例1:
HttpCookie userInfo = new HttpCookie("userInfo"); userInfo["UserName"] = "Annathurai"; userInfo["UserColor"] = "Black"; userInfo.Expires.Add(new TimeSpan(0, 1, 0)); Response.Cookies.Add(userInfo);
示例2:
Response.Cookies["userName"].Value = "Annathurai"; Response.Cookies["userColor"].Value = "Black";
如何从Cookie中检索?
通过Request的帮助,它可以轻松地检索cookie值 宾语。例1:
string User_Name = string.Empty; string User_Color = string.Empty; User_Name = Request.Cookies["userName"].Value; User_Color = Request.Cookies["userColor"].Value;
示例2:
string User_name = string.Empty; string User_color = string.Empty; HttpCookie reqCookies = Request.Cookies["userInfo"]; if (reqCookies != null) { User_name = reqCookies["UserName"].ToString(); User_color = reqCookies["UserColor"].ToString(); }
答案 1 :(得分:0)
您必须确保在Request.QueryString.Iust中有值,以检查您的代码是否适用于cookie的硬代码值,然后从cookie中读取。