我的cookie读写

时间:2023-03-09 03:49:02
我的cookie读写

前后台必须一致,

后台:

public static void SetCookie(string cookieName, string value, int expiresDays)
{
    var newCookie = new HttpCookie(cookieName);
    newCookie.Value = value;
    newCookie.Expires = DateTime.Now.AddDays(expiresDays);
    newCookie.Path = "/";
    System.Web.HttpContext.Current.Response.AppendCookie(newCookie);
}

public static string GetCookie(string cookieName)
{
    if (System.Web.HttpContext.Current.Request.Cookies[cookieName] != null
        && !string.IsNullOrEmpty(System.Web.HttpContext.Current.Request.Cookies[cookieName].Value))
    {
        string value = System.Web.HttpContext.Current.Request.Cookies[cookieName].Value;
        return HttpUtility.UrlDecode(value);
    }

return null;
}

调用者:

CookieHelper.SetCookie(ckIdName, "0", 7);

userId = CookieHelper.GetCookie(ckIdName)

前台:

$.cookie('productIds', "," + productId, { expires: 7, path: '/' });

必须一致才能进行修改。