How to create persistent cookies in asp.net?

2020-01-25 04:38发布

I am creating cookies with following lines:

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

Now How to make it persistent?

Because if I visit the same page again after closing the browser, I'm unable to get it back.

6条回答
老娘就宠你
2楼-- · 2020-01-25 05:13

FWIW be very careful with storing something like a userid in a cookie unencrypted. Doing this makes your site very prone to cookie poisoning where users can easily impersonate another user. If you are considering something like this I would highly recommend using the forms authentication cookie directly.

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);

Then you can read this at any time from an ASP.NET page by doing

string userId = null;
if (this.Context.User.Identity.IsAuthenticated) 
{
    userId = this.Context.User.Identity.Name;
}
查看更多
欢心
3楼-- · 2020-01-25 05:19

As I understand you use ASP.NET authentication and to set cookies persistent you need to set FormsAuthenticationTicket.IsPersistent = true It is the main idea.

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);
查看更多
爷、活的狠高调
4楼-- · 2020-01-25 05:24

Although the accepted answer is correct, it does not state why the original code failed to work.

Bad code from your question:

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

Take a look at the second line. The basis for expiration is on the Expires property which contains the default of 1/1/0001. The above code is evaluating to 1/1/0002. Furthermore the evaluation is not being saved back to the property. Instead the Expires property should be set with the basis on the current date.

Corrected code:

HttpCookie userid = new HttpCookie("userid", objUser.id.ToString());
userid.Expires = DateTime.Now.AddYears(1);
Response.Cookies.Add(userid);
查看更多
成全新的幸福
5楼-- · 2020-01-25 05:34

You need to add this as the last line...

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

When you need to read the value of the cookie, you'd use a method similar to this:

    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;
查看更多
干净又极端
6楼-- · 2020-01-25 05:35

Here's how you can do that.

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.
}
查看更多
太酷不给撩
7楼-- · 2020-01-25 05:39

//add cookie

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

//read cookie

    var httpCookie = Request.Cookies["panelIdCookie"];
                if (httpCookie != null)
                {
                    panelId = Convert.ToInt32(httpCookie["panelId"]);
                }
查看更多
登录 后发表回答