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

时间:2023-01-02 16:57:21

I have this code in 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;
    }

But when I run my website below error was shown:

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

Request is not available in this context

在此上下文中不提供请求

Why?

为什么?

1 个解决方案

#1


1  

Application_Start is called once before any ASP files are processed. That is why Request is not available yet.

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

You want to use Application_BeginRequest which is called on each request.

您希望使用在每个请求上调用的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

Global.aspx中的Application_Start与Application_BeginRequest事件

#1


1  

Application_Start is called once before any ASP files are processed. That is why Request is not available yet.

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

You want to use Application_BeginRequest which is called on each request.

您希望使用在每个请求上调用的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

Global.aspx中的Application_Start与Application_BeginRequest事件