添加标头时在 end_request 中抛出异常

Eri*_*sch 5 c# asp.net-mvc global-asax http-headers

偶尔我会抛出这个异常(在 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
Run Code Online (Sandbox Code Playgroud)

该行对应于:

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");
}
Run Code Online (Sandbox Code Playgroud)

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

Jon*_*ams 3

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

如果您确实想将其保留在 中Application_EndRequest,则可以打开输出缓冲(Response.BufferOutput = true;提前在某处,例如 中Page_Load),以便在请求完全处理之前不会发送标头。不过,输出缓冲有利有弊,因此如果您想尝试的话,请务必阅读相关内容。

  • 我会把它放在 Application_PreSendRequestHeaders 中 (8认同)
  • 据此,在托管代码中使用 PreSendRequestHeaders 是一个坏主意:http://www.asp.net/aspnet/overview/web-development-best-practices/what-not-to-do-in-aspnet,-and -代替做什么#presend (2认同)