【问题标题】:Cookie expiration time not working in C#Cookie过期时间在C#中不起作用
【发布时间】:2018-03-28 13:50:19
【问题描述】:

我无法设置持久性 cookie。它仅成为会话。

我知道同样的问题已经问过here,但即使我做了所有的步骤,我也无法解决它。
(无法使用 Fiddler 进行测试)。

我的代码是:

/// Default.aspx.cs methods :

protected void Page_Load(object sender, EventArgs e)
{
    if (! Cookies.CookieExist("kuki"))
    {
        Cookies.CreateCookie("kuki");
    }
    Fill();
}    

private void Fill()
{
    string a = Cookies.GetCookieValue("kuki", "key");

    if (!a.Contains("data"))
    {
        return;
    }
    // codes for a
}

protected void ButtonAdd_Click(object sender, EventArgs e)
{
    if (TextBox1.Text != string.Empty)
    {
        Cookies.InsertCookie("kuki", "key", TextBox1.Text);
    }        
}


/// Cookie class methods:

public static void InsertCookie(string Cookie, string Key, string Data)
{
    HttpCookie Kuki = HttpContext.Current.Request.Cookies[Cookie];
    Kuki[Key] = Data;
    HttpContext.Current.Response.SetCookie(Kuki);
}

public static bool CookieExist(string Cookie)
{
    HttpCookie cookie = HttpContext.Current.Request.Cookies[Cookie];
    if (cookie == null)
    {
        return false;
    }
    else
    {
        return true;
    }
}

public static void CreateCookie(string Cookie)
{
    HttpCookie cookie = new HttpCookie(Cookie);
    cookie.Expires = DateTime.Now.AddYears(1);
    HttpContext.Current.Response.Cookies.Set(cookie);
}

public static string GetCookieValue(string CookieName, string CookieKey)
{
    HttpCookie cookie = HttpContext.Current.Request.Cookies[CookieName];
    try
    {
        if (cookie != null)
        {
            return cookie[CookieKey].ToString();
        }
        else
        {
            return "";
        }
    }
    catch (Exception)
    {
        return "";
    }        
}

我使用 Chrome。
我该如何解决这个问题?

更新:

添加了按钮和 InsertCookie 方法。

【问题讨论】:

    标签: c# asp.net cookies session-cookies


    【解决方案1】:

    代替

    public static void CreateCookie(string Cookie)
    {
        HttpCookie cookie = new HttpCookie(Cookie);
        cookie.Expires = DateTime.Now.AddYears(1);
        HttpContext.Current.Response.Cookies.Set(cookie);
    }
    

    试试

    public static void CreateCookie(string Cookie)
    {
        HttpCookie cookie = new HttpCookie(Cookie);
        cookie.Expires = DateTime.Now.AddYears(1);
        HttpContext.Current.Response.Cookies.Add(cookie);   //<-- Add
    }
    

    使用Add 添加一个cookie。仅当您需要更新已写入响应的 cookie 时才使用Set(几乎永远不会)。

    【讨论】:

      【解决方案2】:

      我知道错误是什么。 我试图在我的 cookie 上存储数据。 但是,例如,我应该只将我的 cookie 用于记住我的方法。 对不起。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2017-11-10
        • 1970-01-01
        • 1970-01-01
        • 2019-09-06
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多