1

当用户访问我的网页时,我试图设置一个 cookie。cookie 的值是我存储在数据库中的唯一编号,用于跟踪用户何时返回我的网站。我在 global.asax 中设置了 cookie,如下所示:

void Application_BeginRequest()
{
    string cookievalue = "";
    string a = "";
    try
    {
        a = GetCookie();
        if (!string.IsNullOrEmpty(a))
        {
            cookievalue = a;
        }
        else
        {
            cookievalue = SetCookie();
        }
    }
    catch (Exception ex)
    {

    }
}

在 BeginRequest() 我只想检查 cookie 是否存在。如果存在,则不执行任何操作并保留 cookie 中已经存在的值。如果它不存在,则设置 cookie 并添加一个值。

public static string GetCookie()
{
    string cookievalue = "";
    try
    {
        if (HttpContext.Current.Request.Cookies["TestCookie"] != null)
            cookievalue = HttpContext.Current.Response.Cookies["TestCookie"].Value;
    }
    catch (Exception ex)
    {
        //
    }

    return cookievalue;
}
public static string SetCookie()
{
    string cookievalue = "";
    try
    {
        HttpCookie myCookie = new HttpCookie("TestCookie");
        // Set the cookie value.
        myCookie.Value = "1234"; //1234 is my unique number
        myCookie.Expires = DateTime.Now.AddYears(50);
        HttpContext.Current.Response.Cookies.Add(myCookie);
        cookievalue = id;
    }
    catch (Exception ex)
    {
        //
    } 
    return cookievalue;
}

问题是每次我重新加载页面时,“TestCookie”都会被重写为一个新值。我一直在阅读 MSDN,了解 cookie 如何存储在 ASP.NET 中,并根据说明,它应该可以正常工作。我一定做错了什么,我看不到它。我将所有这些代码放在一个普通页面中,例如 test.aspx.cs 以尽早对其进行测试,但结果相同,并决定将其移至应用程序级别,看看这是否会产生任何影响,但它没有:(。

4

0 回答 0