C# persistent cookie

本文关键字:cookie persistent | 更新日期: 2023-09-27 18:20:41

我在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值?

C# persistent cookie

尝试使用以下代码:-

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?在借助响应对象或HttpCookie的Asp.Net

示例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的帮助从cookes中检索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();
    }

您必须确保您在Request.QueryString.中有值。只是为了检查您的代码是否能有效地执行cookie的代码值,然后从cookie中读取。