Exception thrown in end_request when adding headers

回眸只為那壹抹淺笑 提交于 2019-12-10 08:02:01

问题


Occasoinally i get this exception thrown (viewable in 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

This line corresponds to:

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");
}

Is there a more appropriate place to do this? I know the EndRequest seems kind of odd, but every example of people using this places it here.


回答1:


Application_BeginRequest would be a better place to do it. Unless maybe you have some reason somewhere else in your application for waiting until the end, though I can't think of a good reason in common cases.

If you really want to keep it in Application_EndRequest, you can turn on output buffering (Response.BufferOutput = true; somewhere early, like in Page_Load) so headers aren't sent until the request is completely processed. There are pros and cons to output buffering though, so make sure you read up on that if you want to try it.




回答2:


For the benefit of those landing here, there's another way of adding X-UA-Compatible (or any other such header). You can also include X-UA-Compatible as a meta tag in your master page OR default.cshtml like so:

<meta http-equiv="X-UA-Compatible" content="IE=Edge" />

This technique is the easiest to implement especially on shared hosting where you may not be able to tweak IIS settings too easily. A great discussion on stackoverflow can be found here.



来源:https://stackoverflow.com/questions/7198205/exception-thrown-in-end-request-when-adding-headers

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!