应用程序部署到服务器时未调用Application_EndRequest

时间:2014-12-18 16:02:06

标签: c# asp.net-mvc

在我的Global.asax.cs文件中,我有以下方法:

protected virtual void Application_BeginRequest() {
    HttpContext.Current.Items["message"] = "Hello World";
}

protected virtual void Application_EndRequest() {
    string message = (string)HttpContext.Current.Items["message"];
    if (String.IsNullOrEmpty(message)) {
        HttpContext.Current.Response.Write("<!-- Empty Message! -->");
    }
    else {
        HttpContext.Current.Response.Write("<!-- Message: " + message + " -->");
    }
}

当我在本地运行时,在结束</html>标记后输出消息。

当我部署到测试服务器时,不输出消息,甚至不输出<!-- Empty Message! -->消息。我甚至可以添加代码来在Application_EndRequest方法中抛出一个永远不会被抛出的异常。

我已经将此方法用于以前的项目,使用VS2010和MVC 4构建,主要用于每个请求解决方案的一个dbcontext,没有任何问题。

我发现这是调查的一部分,关于HttpContext.Current.Items在请求期间丢失值的原因,同样仅在部署到测试服务器时。 (类似于this unresolved problem

使用Visual Studio 2013和MVC 5(即新的MVC应用程序而没有自定义代码),应用程序是“开箱即用”的,因此web.config的更改很少。事实上,唯一的变化是解决空白页面问题

<system.webServer>
    <modules>
        <remove name="UrlRoutingModule-4.0" />
        <add name="UrlRoutingModule-4.0" type="System.Web.Routing.UrlRoutingModule" preCondition="" />
    </modules>
</system.webServer>

有谁知道为什么Application_EndRequest不会在服务器上被调用?

是否还需要其他配置设置?

更新201412191534

我终于让Glimpse工作了。我向TraceInformationApplication_StartApplication_BeginRequest添加了一些Application_EndRequest条消息。在本地运行会显示跟踪消息。将应用程序部署到测试服务器并且不显示任何消息。所以似乎没有一个关于global.asax的方法在服务器上被调用,这可以解释我遗漏的HttpContext.Current.Items - 它们首先没有被设置!

更新201412221010

我现在已经调查了为什么Global.asax中的事件没有被调用并且发现了许多类似的问题:

我尝试过以下建议:   - 确保Global.asax继承自正确的类(它确实);
  - 设置代码断点(由于事件未被触发而永远不会到达)

然后我发现了这一个 - Global.asax not firing for .aspx pages in IIS7建议使用我没有使用的<modules runAllManagedModulesForAllRequests="true">,因为我使用了将以下内容添加到modules部分的方法

<remove name="UrlRoutingModule-4.0" />
<add name="UrlRoutingModule-4.0" type="System.Web.Routing.UrlRoutingModule" preCondition="" />

因为每个人都建议不要使用runAllManagedModulesForAllRequests="true"。请参阅此文Don't use runAllManagedModulesForAllRequests="true" when getting your MVC routing to work

然而,在一次绝望的尝试中,我使用了这个邪恶的属性,猜猜是什么?事件开始再次被解雇!

我们尚未应用hotfix,我还没有找到如何将模块添加到modules部分,即我的应用程序的正确语法。

1 个答案:

答案 0 :(得分:0)

由global.asax文件表示的HttpApplication实例是一个仅代表第一个 HttpApplication对象的实例。无法保证此HttpApplication实例将用于任何其他请求。

您需要覆盖global.asax和中的Init()方法方法挂钩您想要的任何事件:

public override void Init() {
    base.Init();

    EndRequest += MyEventHandler;
}

有关HttpApplication对象的更多信息,请参阅this MSDN article

找到了这个答案here