0

そのため、Web サイトをホワイトリストに登録するためのシステムを追加しました。これが私の 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 に答える