0

所以我只是添加了一个将我的网站列入白名单的系统。这是我的 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 方法可以访问。

4

1 回答 1

0

好的,所以我想通了。我必须使列表静态。我假设每次发出新请求时都会实例化一个新的 Global 类。谁能向我解释为什么 MVC 会这样做?

于 2012-05-16T02:29:37.037 回答