1

我在 global.asax 中有这段代码

void Application_Start(object sender, EventArgs e)  
    {  
       // Code that runs on application startup  
        if (Request.Cookies["mylang"] == null)  
        {  
            HttpCookie mylang = new HttpCookie("mylang");  
            mylang.Value = "fa";
            mylang.Expires = DateTime.Now.AddYears(1);
            Response.Cookies.Add(mylang);
            Session.Add("mylang", "fa");
        }
        Thread.CurrentThread.CurrentUICulture = new CultureInfo(Request.Cookies["mylang"].Value);
        Thread.CurrentThread.CurrentCulture = CultureInfo.CreateSpecificCulture(Request.Cookies["mylang"].Value);
        Session["mylang"] = Request.Cookies["mylang"].Value;
    }

但是当我运行我的网站时,显示以下错误:

请求在此上下文中不可用

为什么?

4

1 回答 1

1

Application_Start在处理任何 ASP 文件之前调用一次。这就是Request尚不可用的原因。

您想使用在每个请求上调用的Application_BeginRequest 。

void Application_BeginRequest(object sender, EventArgs e)
{
   Config.Init();

   // Code that runs on application startup
   if (Request.Cookies["mylang"] == null)
   {
      ...
   }
}

Global.aspx 中的 Application_Start 与 Application_BeginRequest 事件

于 2013-05-21T21:37:11.530 回答