gpt4 book ai didi

C# 持久性 cookie

转载 作者:行者123 更新时间:2023-11-30 17:46:48 27 4
gpt4 key购买 nike

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

最佳答案

试试下面的代码:-

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 的类型:-

Non-Persist Cookie - A cookie has expired time Which is called as Non-Persist Cookie

How to create a cookie? Its really easy to create a cookie in the Asp.Net with help of Response object or HttpCookie

Example 1:

    HttpCookie userInfo = new HttpCookie("userInfo");
userInfo["UserName"] = "Annathurai";
userInfo["UserColor"] = "Black";
userInfo.Expires.Add(new TimeSpan(0, 1, 0));
Response.Cookies.Add(userInfo);

Example 2:

    Response.Cookies["userName"].Value = "Annathurai";
Response.Cookies["userColor"].Value = "Black";

How to retrieve from cookie?

Its easy way to retrieve cookie value form cookes by help of Request object. Example 1:

    string User_Name = string.Empty;
string User_Color = string.Empty;
User_Name = Request.Cookies["userName"].Value;
User_Color = Request.Cookies["userColor"].Value;

Example 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();
}

关于C# 持久性 cookie,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25683810/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com