最近浏览过的商品(保存到cookie)

把商品Id累加到cookie的value

  /// <summary>
    /// 最近浏览过的商品
    /// </summary>
    /// <returns></returns>
    protected string GetRecentBrowsing()
    {
        StringBuilder sb = new StringBuilder();

        if (Request.Cookies["only"] != null)
        {

//拆分cookie的值,取到浏览过的商品id
            string[] ntw=Request.Cookies["only"].Value.Split(',');
            int j = 0;
            for (int i =ntw.Length; i >= 1; i--)
            {
                if (j > 10) break;


                Rjob rjob = new Rjob();
                DataTable djob = rjob.GetDataTable("c_job", ntw[i-1]);
                if (djob.Rows.Count > 0)
                {
                    sb.Append("<li>");
                    sb.AppendFormat("<p><span class=\"cor\">&#9642;&nbsp;</span><a title=\"{0}\" href=\"{1}\">{0}</a></p>", djob.Rows[0]["position"].ToString(), rooturl + "job/index.aspx?pid=" + Convert.ToInt32(djob.Rows[0]["id"].ToString()));
                    sb.Append("</li>");
                }
                j++;
               
            }
        }

        return sb.ToString();
    }

/// <summary>
    /// 写入cookie
    /// </summary>
    /// <param name="name">cookie名字</param>
    /// <param name="value">cookie值</param>
    protected void writeCookie(string name, string value)
    {
        if (Request.Cookies[name] == null)  //第一次写cookie
        {
            HttpCookie aCookie = new HttpCookie(name);
            aCookie.Value = value + ",";
            aCookie.Expires = DateTime.Now.AddDays(1);
            Response.Cookies.Add(aCookie);

        }
        else
        {

//判断商品id
            if (Request.QueryString["pid"] != null && Request.QueryString["pid"] != "")
            {

//判断现有cookie值是否包含当前商品,如果不包含就累加
                if (!Request.Cookies[name].Value.Contains(Request.QueryString["pid"].ToString() + ","))
                {
                    Request.Cookies[name].Value += value + ",";
                    Request.Cookies[name].Expires = DateTime.Now.AddDays(1);
                    Response.Cookies.Add(Request.Cookies[name]);
                }
            }
        }


    }
    /// <summary>
    /// 读cookie
    /// </summary>
    /// <returns>cookie值</returns>
    protected string readCookie(string name)
    {
        string cookie = string.Empty;
        if (Request.Cookies[name] != null)
        {
            cookie = Request.Cookies[name].Value;
        }
        return cookie;
    }

原文地址:https://www.cnblogs.com/yhdkzy/p/2043984.html