从cookie获取值并存储在数据库中

时间:2009-07-23 22:20:02

标签: c# javascript cookies

我想将搜索网址存储为客户端的cookie并将此网址写回数据库。下面的代码没有显示任何错误但是没有在数据库中写入网址字符串。我使用写入网址单独测试在数据库中它工作正常。只是当我尝试从cookie做时它不工作。如果你有任何建议请给我。

// Javascript part

location.href =“<%= ub.Uri.ToString()%>?” + Math.random()+“#”+ query.toString();

document.cookie =“kursearch =”+ query.toString();

// c#代码部分

protected void Page_Load(object sender,EventArgs e)     {

    String text = GetCookie("kursearch");
    Storetxt(text);
}

public string GetCookie(string cookiename)
{
    string cookyval = "";
    try
    {
        cookyval = Request.Cookies[cookiename].Value;
    }
    catch (Exception e)
    {
        cookyval = "";
    }
    return cookyval;
}

public void Storetxt(String txt)
{


    string connection = "Data Source=.\\SQLEXPRESS;Initial Catalog=PtsKuratlas;Integrated Security=True";
    SqlConnection conn = null;
    SqlCommand cmd = null;
    try
    {
        conn = new SqlConnection(connection);
        cmd = new SqlCommand("INSERT INTO gti_analytics (keywords) VALUES (@link)", conn);
        cmd.CommandType = CommandType.Text;
        cmd.Parameters.AddWithValue("@link", txt);
        conn.Open();
        cmd.ExecuteNonQuery();
    }
    catch (Exception ex)
    {

    }
    finally
    {
        if (cmd != null) cmd.Dispose();
        if (conn != null)
        {
            if (conn.State == ConnectionState.Open) conn.Close();
            conn.Dispose();
        }
    }



}

1 个答案:

答案 0 :(得分:0)

为什么不在拨打服务器之前设置cookie?