错误:请求在此上下文中不可用

时间:2013-05-21 21:06:18

标签: asp.net global-asax

我在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;
    }

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

  

请求在此上下文中不可用

为什么?

1 个答案:

答案 0 :(得分:1)

在处理任何ASP文件之前,会先调用

Application_Start 。这就是请求尚未推出的原因。

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

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

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

Application_Start vs Application_BeginRequest event in Global.aspx