C#无法写入cookie文件

时间:2012-01-21 00:42:19

标签: c# asp.net

我试图通过以下代码编写一个cookie文件来存储userID和userPw,但是我的代码有问题,返回给我的输出总是“cookies文件不存在”。

protected void writeCookie(object sender, EventArgs e)
{
    if (Request.Cookies["save"] == null)
    {
        HttpCookie cookie = new HttpCookie("save");
        cookie.Value = "testing" + "testing2";
        cookie.Expires = DateTime.Now.AddMinutes(5);
        Request.Cookies.Add(cookie);
    }
    else
    {
        Response.Write("cookie existed");
    }
}

protected void ReadCookies(object sender, EventArgs e)
{
    if (Request.Cookies["save"] != null)
    {
        Response.Write(Request.Cookies["save"].Value);
    }
    else
    {
        Response.Write("cookies file not exist");
    }
}

1 个答案:

答案 0 :(得分:4)

您可能无法首先创建Cookie,请尝试更改

Request.Cookies.Add(cookie);

Response.Cookies.Add(cookie);

来源:http://msdn.microsoft.com/en-us/library/aa287547(v=vs.71).aspx