Majid Basirati
Majid Basirati

Reputation: 2855

Error: Request is not available in this context

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

Upvotes: 1

Views: 1874

Answers (1)

Win
Win

Reputation: 62260

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

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

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

Upvotes: 1

Related Questions