0

So I just added a system for whitelisting my website. Here is my Global.asax. I have commented the troubled areas

#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

I just don't understand why I am having this issue. As far as my understanding goes, after Application_start is called, the list should fill and then be accessible to the _BeginRequest Method.

Adam Schiavone
  • 2,412
  • 3
  • 32
  • 65

1 Answers1

0

Ok, so I figured it out. I had to make the list static. I would assume that a new Global class is instantiated every time a new request is made. Could anyone explain to me why MVC does that?

Adam Schiavone
  • 2,412
  • 3
  • 32
  • 65