添加标头时在end_request中抛出exception
偶尔我会抛出这个exception(在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
),因此在完全处理请求之前不会发送标头。 虽然输出缓冲有利有弊,所以如果你想尝试它,请务必阅读。
为了这里登陆的人的利益,还有另一种添加X-UA-Compatible(或任何其他此类标头)的方法。 您还可以在主页面中包含X-UA-Compatible作为元标记,或者像这样包含default.cshtml:
这种技术最容易实现,特别是在共享主机上,您可能无法轻松调整IIS设置。 关于stackoverflow的一个很好的讨论可以在这里找到。