添加标头时 end_request 抛出异常

2024-01-28

有时我会抛出此异常(可在 elmah 中查看)

System.Web.HttpException: 
Server cannot append header after HTTP headers have been sent.

System.Reflection.TargetInvocationException: Exception has been thrown by the target 
of an invocation. ---> System.Web.HttpException: Server cannot append header after 
HTTP headers have been sent.
   at System.Web.HttpHeaderCollection.SetHeader(String name, String value, 
       Boolean replace)
   at System.Web.HttpHeaderCollection.Add(String name, String value)
   at BettingOnYou.MvcApplication.Application_EndRequest() in /Global.asax.cs:line 55

该行对应于:

protected void Application_EndRequest()
{
    // By default, IE renders pages on the intranet (same subnet) in compatibility mode.  
    // IE=edge forces IE to render in it's moststandard mode possible.  
    // IE8 Standards in IE8, IE9 Standardss in IE9, etc..
    //
    // Chrome=1 causes ChromeFrame to load, if installed.  This allows IE6 to use
    // a Chrome frame to render nicely.
    Response.Headers.Add("X-UA-Compatible", "IE=edge, Chrome=1");
}

有没有更合适的地方可以做到这一点?我知道 EndRequest 看起来有点奇怪,但每个使用它的人的例子都把它放在这里。


Application_BeginRequest将是一个更好的地方。除非您在申请中的其他地方有某种原因要等到最后,但在常见情况下我想不出一个好的理由。

如果你真的想保留它Application_EndRequest,您可以打开输出缓冲(Response.BufferOutput = true;早期的某个地方,比如Page_Load),因此在请求完全处理之前不会发送标头。不过,输出缓冲有利有弊,所以如果您想尝试的话,请务必阅读相关内容。

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

添加标头时 end_request 抛出异常 的相关文章

随机推荐