c# - 无法在 ASP.NET 中更新 cookie

标签 c# asp.net-mvc model-view-controller cookies

我快疯了。我可以写入 cookie,然后再读取它。但在某些时候,我想更新它所持有的值(value)。每当我再次获得 cookie 时,我都会得到初始值,而不是更新后的值。下面是我用于写入/更新和读取 cookie 的代码。

    private static HttpCookie WriteCookie(Guid siteId, string siteName)
    {
        var cookie = HttpContext.Current.Request.Cookies.Get("UserSettings");
        if(cookie != null) {
            cookie.Value = EncryptObject(new UserSettingsModel { SiteID = siteId, SiteName = siteName });
            HttpContext.Current.Response.Cookies.Set(cookie);
        }else {
            cookie = new HttpCookie("UserSettings") { Path = "/", Expires = DateTime.Now.AddDays(1), Value = EncryptObject(new UserSettingsModel { SiteID = siteId, SiteName = siteName }) };
            HttpContext.Current.Response.Cookies.Add(cookie);
        }
        return cookie;
    }

    public static UserSettingsModel GetUserSettings(string username = null)
    {
        var cookie = HttpContext.Current.Request.Cookies.Get("UserSettings");
        if (cookie == null || string.IsNullOrEmpty(cookie.Value))
        {
            cookie = ResetUserSettings();
        }
        var userSettings = DecryptObject<UserSettingsModel>(cookie.Value);
        if (userSettings != null)
        {
            var siteId = userSettings.SiteID;
            var siteName = userSettings.SiteName;
            return new UserSettingsModel { SiteID = siteId, SiteName = siteName };
        }
        throw new SecurityException("You have no site attached to your user. Contact an administrtor.");
    }

GetUserSettings 始终返回最初创建 cookie 时使用的值。怎么了?

编辑:

我尝试直接从 Controller 中的方法调用 WriteCookie。 cookie 现已设置。我通常通过 Ajax 请求调用 WriteCookie。现在,我真的必须使用 JavaScript 编写 cookie,还是只能使用 WriteCookie 来编写?

谢谢!

最佳答案

像这样尝试:

var response = HttpContext.Current.Response;
response.Cookies.Remove("UserSettings");
response.Cookies.Add(cookie);

但我怀疑您的实际问题是您在同一个 HTTP 请求中调用了 WriteCookie 方法和 GetUserSettings 方法,这并不像您想象的那样有效它会或如您所料。

WriteCookie 将 cookie 写入Response,以便它在后续请求 中可用,但 GetUserSettings 读取来自 Request 的 cookie,因此您将获得发起此请求时最初设置的 cookie 的值,这当然是旧值。因此,在调用 WriteCookie 更新用户设置 cookie 的值后,执行重定向并仅在后续请求中使用 GetUserSettings 方法。

此外,在 ASP.NET MVC 中,您通常不想使用静态 HttpContext.Current 对象,而是使用此框架为您提供的抽象。我知道您将这 2 个方法编写为静态方法,但您应该将它们编写为 HttpContextBase 对象的扩展方法,例如。这样你就可以在任何你有这个抽象基类实例的地方调用它们,ASP.NET MVC 在 HTTP 请求的生命周期中在许多常见的地方为你提供这个实例。

关于c# - 无法在 ASP.NET 中更新 cookie,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8908345/

相关文章:

ios - 了解uiview和uiviewcontroller

c# - 我如何重构/扩展以下模型

c# - 如何查找 OData edm 模型类型到 clr 类型的映射?

c# - ASP.NET MVC 中的复选框禁用属性

c# - 检测何时出现验证错误

php - 关于 MVC 中 header 的问题

java - 避免变更传播

c# - 跨多个连接的共享事务,或 PostgreSQL 中的 ReadUncommitted

c# - 捕获所有 Windows 7 触摸事件,而不仅仅是在我的窗体具有焦点时捕获

c# - EntityType' 是一个变量,但在使用反射时像类型一样使用