2012-05-16 37 views
0

所以我只是添加了一個白名單我的網站的系統。 這是我的Global.asax。我已經評論了困擾地區Global.asax列表重置本身

#region Application Methods 

    private List<string> _approvedIps = new List<string>(); 

    protected void Application_BeginRequest() 
    { 
     //This is obviously called afterwards 
     //But when I examine the list at a breakpoint the count is 0. WHY?!?!? 
     Debug.WriteLine("User from ip: {0}", Request.UserHostAddress); 
     if (!_approvedIps.Contains(Request.UserHostAddress)) 
     { 
      Debug.WriteLine("Unauthorized user. Access Denied"); 
      Response.Clear(); 
      Response.StatusCode = (int) HttpStatusCode.Unauthorized; 
      Response.End(); 
     } 
    } 

    protected void Application_Start() 
    { 
     string path = Path.Combine(Server.MapPath("~"), "whitelist.txt"); 
     using (var reader = new StreamReader(path)) 
     { 
      while (reader.Peek() > 0) 
      { 
       string l = reader.ReadLine(); //Reader here works fine and at a breakpoint 
       _approvedIps.Add(l);   //I can see the count of 2 
      } 
     } 
     Database.SetInitializer(new IYCDataDBInit(50)); 
     AreaRegistration.RegisterAllAreas(); 

     RegisterGlobalFilters(GlobalFilters.Filters); 
     RegisterRoutes(RouteTable.Routes); 

     BundleTable.Bundles.RegisterTemplateBundles(); 
    } 

    #endregion 

我只是不明白爲什麼我有這個問題。 據我瞭解,在調用Application_start之後,該列表應該填充,然後可以通過_BeginRequest方法訪問。

回答

0

好的,所以我想通了。我不得不讓這個列表變成靜態的。我會假設每次發出新請求時都會實例化一個新的Global類。任何人都可以向我解釋爲什麼MVC會這麼做嗎?