【问题标题】:HttpContext.Current.Request.Cookies doesnt load value after reloadHttpContext.Current.Request.Cookies 重新加载后不加载值
【发布时间】:2015-08-20 19:22:32
【问题描述】:

我正在开发一个多语言 C# 网站。我写了一个databaselanguages文件和Languages类。在这堂课中,我将所有字符串都放在适当的语言中。默认情况下,语言是荷兰语,除非有 cookie。在我使用语言类之前,我把它写在默认的 aspx.cs 中,并像这样请求 cookie:

Context.Request.Cookies ["lancookie"];

如果更改了语言,我更改了 cookie 并重新加载页面。 在我使用的语言课中:

HttpContext.Current.Request.Cookies ["lancookie"].Value;

如果我更改语言,那么它也需要几分钟才能加载。我该怎么做才能触发 cookie?

 

    public class Language
    {

      public static string getLanCookie ()
      {
        lancookie string = string.Empty;
        if (HttpContext.Current.Request.Cookies ["lancookie"]. Value! = null)
        {
            lancookie HttpContext.Current.Request.Cookies = ["lancookie"]. Value;
        }
        else
        {
            lancookie = "Dutch";
        }
        lancookie return;
      }

       public static string language = getLanCookie ()
       public static string Home = Language ("Home", language);
       public static string end = Language ("The End", language);
       public static string Subject = Language ("Box", language);

   }

【问题讨论】:

  • 旁白:如果您使用的是“现代”版本的 Internet Explorer,您可以使用 F12 开发人员工具查看浏览器接收和传输的 cookie。 (其他浏览器可能有类似的工具,但它们可以正常工作。)

标签: c# cookies


【解决方案1】:

你必须使用

HttpContext.Current.Response.Cookies

设置一个新的。为了能够清除 cookie,您必须将其过期日期设置为过去。不会太详细,因为这应该回答你的问题:

When to use Request.Cookies over Response.Cookies?

【讨论】:

  • 这是我现在使用的代码。这有一个延迟。 if (HttpContext.Current.Request.Cookies["lancookie"].Value != null) { HttpContext.Current.Request.Cookies["lancookie"].Expires = DateTime.Now.AddDays(-1); } HttpCookie cookie = new HttpCookie("lancookie") { Value = lan, Expires = DateTime.Now.AddMonths(1) }; HttpContext.Current.Response.Cookies.Add(cookie);
  • 重新加载时,在页面加载之前 cookie 是旧值。但是在页面加载的 response.write 上,cookie 是很好的价值。
  • 我发现当我再次保存语言类时,cookie被直接读取到它的新值。好像是缓存问题。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2018-08-19
  • 2017-03-15
  • 2021-12-02
  • 2012-08-25
  • 1970-01-01
  • 2013-06-03
  • 2017-11-29
相关资源
最近更新 更多