我正在创建具有以下行的cookie:

HttpCookie userid = new HttpCookie("userid", objUser.id.ToString());
userid.Expires.AddYears(1);
Response.Cookies.Add(userid);

现在我怎么才能让它持久呢?

如果在关闭浏览器后再次访问同一页面,我将无法将其取回.

推荐答案

这是你可以做到的.

Writing the persistent cookie.

//create a cookie
HttpCookie myCookie = new HttpCookie("myCookie");

//Add key-values in the cookie
myCookie.Values.Add("userid", objUser.id.ToString());

//set cookie expiry date-time. Made it to last for next 12 hours.
myCookie.Expires = DateTime.Now.AddHours(12);

//Most important, write the cookie to client.
Response.Cookies.Add(myCookie);

Reading the persistent cookie.

//Assuming user comes back after several hours. several < 12.
//Read the cookie from Request.
HttpCookie myCookie = Request.Cookies["myCookie"];
if (myCookie == 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(myCookie.Values["userid"]))
{
    string userId = myCookie.Values["userid"].ToString();
    //Yes userId is found. Mission accomplished.
}

Asp.net相关问答推荐

由于 Blazor Change Detection API,组件重新渲染被跳过.如何避免?

在具有多个项目(API/服务/数据等)的解决方案中编写 SignalR 服务的最佳方法是什么?

'Access-Control-Allow-Origin' 标头包含多个值 '*, *',但只允许一个

ASP.NET Response.Redirect 使用 302 而不是 301

是否可以访问位于另一个项目中的 MVC 视图?

使用 IIS 的 ASP.NET 调试超时

在上下文中找不到 owin.Environment 项

ASP.NET MVC 5 中的路由可选参数

Windows 运行 ASP.NET 的 IIS 替代方案

如何确定服务器端 C# 上的浏览​​器窗口大小

在 ASP.NET MVC 中使用 Razor 创建可重用的 HTML 视图组件

ASP.NET 中的全局资源与本地资源

aspnet_compiler 发现错误版本的 System.Web.WebPages 1.0.0.0 而不是 2.0.0.0

如何在 ASP.NET MVC 中设置时区?

.NET AJAX 调用 ASMX 或 ASPX 或 ASHX?

具有自定义报告创建能力的最佳 ASP.NET 报告引擎

Windows Azure PaaS(网络角色)的真正替代品?

Asp.Net web 服务:我想返回错误 403 禁止

压力测试 ASP.Net 应用程序

jQuery Ajax 调用 - 成功设置变量值