gpt4 book ai didi

c# - 如何在 global.asax 中设置默认的 cookie 值?

转载 作者:行者123 更新时间:2023-11-30 17:03:55 25 4
gpt4 key购买 nike

我想为每个访问该网站的用户创建一个 cookie 并为其设置一个默认值。 cookie 用于以英语启动网站,之后用户可以根据自己的喜好更改语言。

我在 global.asax 中这样做

        HttpCookie myCookie = new HttpCookie("Language"); 
myCookie.Value = "EN";
myCookie.Expires = DateTime.Now.AddDays(1d);
HttpContext.Current.Response.Cookies.Add(myCookie);

我尝试在以下事件中使用上面的代码,

Application_Start
Application_BeginRequest
Session_Start

在上述所有三个事件中,为每次页面加载将 cookie 值设置为“EN”。事实并非如此。当用户选择其他语言时,语言必须设置为 HttpCookie("Language")。

最佳答案

你应该首先检查cookie是否还没有被定义..它是否已经设置你不需要再次设置它..当用户选择一种新的语言时,然后你才应该重新定义它.. . 一般算法和操作顺序是这样的

  • if user is changing language
    • change the language of the application to the chosen
    • save it to cookie
  • else if the previous setting as been preserved in cookie
    • change the language of the application to the preserved
  • else then is new visit
    • change the language of the application to the default
    • set cookie to the default

这应该在每个请求中进行评估..因为用户可以在任何页面更改语言..所以放置代码的正确事件应该是 Application_BeginRequest

这是您的代码。我将语言参数保存在 CurrentUICulture 中,因此不仅可以在应用程序的任何位置查询它,而且框架还使用它来自定义格式。 .我还假设用户可以传递一个名为 lang 的参数,其中包含他想要的语言..

void Application_BeginRequest(object sender, EventArgs e) 
{
//if user is changing language
if(!String.IsNullOrEmpty(HttpContext.Current.Request["lang"]))
{
String sLang = HttpContext.Current.Request["lang"] as String;
//change the language of the application to the chosen
System.Threading.Thread.CurrentThread.CurrentUICulture = new CultureInfo(sLang);
//save it to cookie
HttpCookie myCookie = new HttpCookie("Language");
myCookie.Value = sLang;
myCookie.Expires = DateTime.Now.AddDays(1d);
HttpContext.Current.Response.Cookies.Add(myCookie);
}
//setting as been preserved in cookie
else if(HttpContext.Current.Request.Cookies["Language"])
{
//change the language of the application to the preserved
String sLang = HttpContext.Current.Request.Cookies["lang"].value as String;
System.Threading.Thread.CurrentThread.CurrentUICulture = new CultureInfo(sLang);
}
else//new visit
{
//change the language of the application to the default
System.Threading.Thread.CurrentThread.CurrentUICulture = new CultureInfo("en-us");
//set cookie to the default
HttpCookie myCookie = new HttpCookie("Language");
myCookie.Value = "en-us";
myCookie.Expires = DateTime.Now.AddDays(1d);
HttpContext.Current.Response.Cookies.Add(myCookie);
}
}

关于c# - 如何在 global.asax 中设置默认的 cookie 值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18098056/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com