【问题标题】:Why would Application_Init fire twice when starting debugging in VS2008/Casini?为什么在 VS2008/Casini 中启动调试时 Application_Init 会触发两次?
【发布时间】:2010-07-22 08:01:55
【问题描述】:

为什么在VS2008/Casini中启动调试时Application_Init会触发两次?

是的,它发生在 global.asax 中。虽然看起来相当随机,但只会偶尔发生一次。

【问题讨论】:

  • 你能说得更具体一点吗,它在哪里做的?在 HttpModule 中,在 Global.asax 中?

标签: asp.net asp.net-mvc visual-studio-2008 cassini


【解决方案1】:

我假设您指的是 ASP.NET MVC 应用程序中的 Global.asax 文件。请注意,您的 global.asax 扩展了 System.Web.HttpApplication 例如:

public class MvcApplication : System.Web.HttpApplication
{
    public static void RegisterRoutes(RouteCollection routes)
    {
        // (snip)
    }

    protected void Application_Init()
    {
        // Why is this running twice?
    }

    protected void Application_Start()
    {
        AreaRegistration.RegisterAllAreas();
        RegisterRoutes(RouteTable.Routes);
    }
}

基本上是multiple HttpApplication instances are being instantiated to serve multiple incoming HTTP requests。请求完成后,HttpApplication 实例将返回到池中以再次重用,类似于数据库连接池。

您无法预测将创建多少个 HttpApplication 实例,基本上 ASP.NET 工作进程将创建所需数量的实例,以满足访问您的 Web 应用程序的 HTTP 请求的需求。您的 Application_Init() 被调用两次,因为正在创建 2 个 HttpApplication 实例,即使它只是您运行您的网站。可能是您在被拉入的 HTML 中引用了其他服务器端资源(JavaScript 文件、CSS 等),或者可能是 Ajax 请求。

如果您想保证代码只运行一次,请将其放入 Global.asax 中的 Application_Start() 方法中。 Or use a Bootstrapper

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-01-08
    • 1970-01-01
    • 1970-01-01
    • 2011-01-27
    • 2021-07-08
    • 2014-10-05
    • 1970-01-01
    相关资源
    最近更新 更多