开发者

Exception thrown in end_request when adding headers

开发者 https://www.devze.com 2023-03-30 16:41 出处:网络
Occasoinall开发者_JAVA百科y i get this exception thrown (viewable in elmah) System.Web.HttpException:

Occasoinall开发者_JAVA百科y 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.


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.


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号