如何成功使用existingResponse =“Auto”?

所以我从我的MVC网络应用程序返回详细的400错误响应。 设置existingResponse =“PassThrough”有效,但这不是我想要的。 我不希望暴露所有失败,我只想在我有自定义响应时公开它们。

自动,默认设置,但我故意设置它。 但是,文档说必须设置“SetStatus”标志,但我不知道如何做这样的事情。 我编写了以下四种控制器方法来测试它,只有BadRequestD工作。 其他人设置状态代码和状态就好了,但是正文内容是“错误请求”。

public ActionResult BadRequestA() { Response.StatusCode = 400; return Content("weeeeee"); } public ActionResult BadRequestB() { Response.Status = "400 U DUN MESSED UP"; return Content("weeeeee"); } public ActionResult BadRequestC() { Response.Status = "400 U DUN MESSED UP"; Response.StatusCode = 400; return Content("weeeeee"); } public ActionResult BadRequestD() { Response.StatusCode = 400; Response.TrySkipIisCustomErrors = true; return Content("weeeeee"); } 

但是,文档说必须设置“SetStatus”标志,但我不知道如何做这样的事情

它实际上是在讨论IIS C ++ SDK中IHttpResponse::SetStatus方法的fTrySkipCustomErrors标志/参数(请参阅我在此处添加到文档底部的注释)。 但是在ASP.NET中,标志显示为Response.TrySkipIisCustomErrors 。 所以根据:

http://www.iis.net/configreference/system.webserver/httperrors

Auto =仅在设置了SetStatus标志时才保持响应不变

我希望看到IIS用自己的html错误页面内容替换响应(你可以配置那些内容是什么),除非你设置:

 Response.TrySkipIisCustomErrors = true; 

这就是你所看到的。


其他相关信息,在MVC5中,似乎表明该标志是真的,即使它对于未在WebForms中看不到的未捕获exception是假的。 作为Global.asax的解决方法,我是:

 protected void Application_Error() { var error = Server.GetLastError(); Server.ClearError(); //code to log error here var httpException = error as HttpException; Response.StatusCode = httpException != null ? httpException.GetHttpCode() : (int)HttpStatusCode.InternalServerError; } 

如果您需要具有4xx http状态的自定义响应,并且仍希望使用自定义错误页面,那么您应该执行以下操作:

  • 在web.config中设置existingResponse="Auto" ;
  • 在您的操作中设置TrySkipIisCustomErrors = true (返回4xx状态和内容的那个);
  • 清除global.asax中的服务器错误(在Application_Error()Server.ClearError() )并重新设置状态代码( Reponse.StatusCode = ((HttpException)Server.GetLastError()).GetHttpCode()

很遗憾,IIS团队没有为特定的状态代码实现existingResponse属性,因此不可能仅针对一个(或几个)代码使用existingResponse="PassThrough"