无法在ASP.NET中更新cookie

And*_*eas 12 c# cookies model-view-controller asp.net-mvc

我为此疯狂.我可以写一个cookie,然后再读一遍.但在某些时候,我想更新它所拥有的价值.每当我再次获得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.");
    }
Run Code Online (Sandbox Code Playgroud)

GetUserSettings始终返回最初创建cookie的值.怎么了?

编辑:

我尝试直接从Controller中的方法调用WriteCookie.现在已经设置了cookie.我通常通过Ajax请求调用WriteCookie.现在,我是否真的必须使用JavaScript编写cookie,或者我可以使用WriteCookie以某种方式进行编写?

谢谢!

Dar*_*rov 17

试试这样:

var response = HttpContext.Current.Response;
response.Cookies.Remove("UserSettings");
response.Cookies.Add(cookie);
Run Code Online (Sandbox Code Playgroud)

但我怀疑你的实际问题是你在同一个HTTP请求中调用WriteCookie方法和GetUserSettings方法,这个方法和方法不像你想象的那样或者你可能期望的那样工作.

该WriteCookie写入cookie来响应,以便它可以在随后的请求,但GetUserSettings在读取cookie 请求所以你得到时,这一要求被启动这当然是旧值,最初设置cookie的值.因此,在调用WriteCookie更新用户设置cookie的值后,执行重定向并仅在后续请求中使用该GetUserSettings方法.

同样在ASP.NET MVC中,您通常不希望使用静态HttpContext.Current对象,而是使用此框架为您提供的抽象.我知道你把这两个方法写成静态但你应该把它们写成HttpContextBase对象的扩展方法,例如.通过这种方式,您可以在具有此抽象基类实例的任何位置调用它们,ASP.NET MVC在HTTP请求的生命周期中为您提供许多常见位置.