如何在ASP.NET中创建持久cookie?

如何在ASP.NET中创建持久cookie?,asp.net,cookies,Asp.net,Cookies,我正在创建具有以下行的cookie: HttpCookie userid = new HttpCookie("userid", objUser.id.ToString()); userid.Expires.AddYears(1); Response.Cookies.Add(userid); 现在我怎样才能使它持久 如果在关闭浏览器后再次访问同一页面,我将无法将其取回。您需要将此添加为最后一行 HttpContext.Current.Response.Cookies.Add(

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

HttpCookie userid = new HttpCookie("userid", objUser.id.ToString());
userid.Expires.AddYears(1);
Response.Cookies.Add(userid);
现在我怎样才能使它持久


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

您需要将此添加为最后一行

HttpContext.Current.Response.Cookies.Add(userid);
当您需要读取cookie的值时,您可以使用类似以下的方法:

    string cookieUserID= String.Empty;

    try
    {
        if (HttpContext.Current.Request.Cookies["userid"] != null)
        {
            cookieUserID = HttpContext.Current.Request.Cookies["userid"];
        }
    }
    catch (Exception ex)
    {
       //handle error
    }

    return cookieUserID;

这是你可以做到的

写入持久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);
//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.
}
读取持久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);
//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.
}
//假设用户几个小时后回来。有好几个<12。
//从请求中读取cookie。
HttpCookie mycokie=Request.Cookies[“mycokie”];
如果(mycokie==null)
{
//未找到cookie或cookie已过期。
//在这里处理情况,重定向用户或直接返回;
}
//确定-找到cookie。
//优雅地检查cookie是否具有预期的键值。
如果(!string.IsNullOrEmpty(mycokie.Values[“userid”]))
{
字符串userId=mycokie.Values[“userId”].ToString();
//是,找到用户ID。任务完成。
}

FWIW在未加密的cookie中存储用户标识之类的内容时要非常小心。这样做会使您的站点很容易发生cookie中毒,用户可以很容易地模拟其他用户。如果您正在考虑类似的问题,我强烈建议您直接使用表单验证cookie

bool persist = true;

var cookie = FormsAuthentication.GetAuthCookie(loginUser.ContactId, persist);

cookie.Expires = DateTime.Now.AddMonths(3);

var ticket = FormsAuthentication.Decrypt(cookie.Value);

var userData = "store any string values you want inside the ticket
                 extra than user id that will be encrypted"

var newTicket = new FormsAuthenticationTicket(ticket.Version, ticket.Name,
     ticket.IssueDate, ticket.Expiration, ticket.IsPersistent, userData);

cookie.Value = FormsAuthentication.Encrypt(newTicket);

Response.Cookies.Add(cookie);
然后,您可以通过执行以下操作随时从ASP.NET页面阅读此内容

string userId = null;
if (this.Context.User.Identity.IsAuthenticated) 
{
    userId = this.Context.User.Identity.Name;
}
//添加饼干

var panelIdCookie = new HttpCookie("panelIdCookie");
panelIdCookie.Values.Add("panelId", panelId.ToString(CultureInfo.InvariantCulture));
panelIdCookie.Expires = DateTime.Now.AddMonths(2); 
Response.Cookies.Add(panelIdCookie);
//阅读曲奇

    var httpCookie = Request.Cookies["panelIdCookie"];
                if (httpCookie != null)
                {
                    panelId = Convert.ToInt32(httpCookie["panelId"]);
                }

虽然接受的答案是正确的,但它没有说明原始代码无法工作的原因

问题中的错误代码:

HttpCookie userid = new HttpCookie("userid", objUser.id.ToString());
userid.Expires.AddYears(1);
Response.Cookies.Add(userid);
看看第二行。过期的依据是Expires属性,该属性包含默认值1/1/0001。上述代码的计算结果为1/1/0002。此外,评估不会保存回属性。相反,Expires属性应以当前日期为基础进行设置

更正代码:

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

据我所知,您使用ASP.NET身份验证,要设置Cookie持久性,您需要设置FormsAuthenticationTicket.IsPersistent=true 这是主要思想

bool isPersisted = true;
var authTicket = new FormsAuthenticationTicket(
1,
user_name, 
DateTime.Now,
DateTime.Now.AddYears(1),//Expiration (you can set it to 1 year)
isPersisted,//THIS IS THE MAIN FLAG
addition_data);
    HttpCookie authCookie = new HttpCookie(FormsAuthentication.FormsCookieName, authTicket );
    if (isPersisted)
        authCookie.Expires = authTicket.Expiration;

HttpContext.Current.Response.Cookies.Add(authCookie);

他说的是FormsAuthenticationCookie吗?既然你知道类型,为什么还要使用
var
。谢谢你的安全顾虑,但我正在对cookies使用加密!因为变量的冗余规范是冗余的。由于问题明确显示userid作为存储在cookie中的值,FormsAuth cookie是此IMO最正确的解决方案。@KimJongWoo即使不为应用程序使用forms auth,您仍然可以使用这些函数生成安全cookies我不需要指定此cookie为授权cookie的任何内容吗?读取持久cookie代码对我来说不起作用。请参阅本文中我的答案。您的代码在功能上与原始问题中发布的代码没有什么不同,只是cookie在12小时内过期,OP在一年内过期。@Ortund指出,有一个关键区别,OP添加到默认时间0001/01/01,而此答案添加到当前时间。