所以我刚刚添加了一个系统,用于将我的网站列入白名单。 这是我的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 :(得分:0)
好的,所以我明白了。我必须使列表静态。我假设每次发出新请求时都会实例化一个新的Global类。任何人都可以向我解释为什么MVC会这样做吗?