C#Cookies不会立即刷新cookie

时间:2015-07-23 13:54:18

标签: c# cookies

我目前在网络应用程序中遇到cookie问题。

首先,我在控制器中创建了2个通用方法,以简化我的cookie操作。他们在这里:

    public bool SetCookie<T>(string key, T value)
    {
        try
        {
            string str = Utils.JSONParser.Serialize(value);
            var cookie = new HttpCookie(key, Utils.JSONParser.Serialize(value))
            {
                HttpOnly = true
            };
            cookie.Expires = DateTime.UtcNow.AddDays(365);
            Response.SetCookie(cookie);
            return true;
        }
        catch (Exception ex)
        {
            throw ex;
        }
    }

    public T GetCookie<T>(string key)
    {
        T obj;
        if (Request.Cookies[key] != null)
        {
            HttpCookie cookie = Request.Cookies.Get(key);
            obj = Utils.JSONParser.Deserialize<T>(cookie.Value);
            return obj;
        }
        return (typeof(T) == typeof(int) ? (T)(object)-1 : default(T));
    }

请注意,这些方法与某些“正常”使用完美配合。 (Utils.JSONParser是JavaScriptSerializer的简单封装。

我使用此代码遇到问题:

 public ActionResult Index(int LineNumber = -1)
    {
        IndexViewModel model = new IndexViewModel();

        if (LineNumber != -1)
            this.SetCookie("lineNumber", LineNumber);

        model.LineNumber = this.GetCookie<int>("lineNumber");
        ....
    }

这里,LineNumber的值例如是5,而当前的cookie值是(例如)20。所以,这里我想要删除20,然后放5。但这不会发生。我必须通过这个方法2次(以5作为参数)最终将5存储在cookie值中。

所以我的问题是,是否有加载时间存储cookie?哪个会解释这个?或者我只是错过了什么?

1 个答案:

答案 0 :(得分:2)

注意当GetCookie方法从您的请求中获取值时,Import-CSV方法如何更改响应。因此,只有当您完成整个请求处理然后获得第二个请求时,请求中设置的cookie才会是您在第一个响应中设置的cookie。

相关问题