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

时间:2013-08-16 15:02:15

标签: c# asp.net-mvc iis

所以我从我的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");
}

2 个答案:

答案 0 :(得分:38)

  

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

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

  

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

     

Auto =仅在SetStatus标志设置为

时才保持响应不变

我希望看到IIS在默认情况下用自己的html错误页面内容替换响应(您可以配置该内容是什么),除非您设置:

Response.TrySkipIisCustomErrors = true;

你正在看到的是什么。


其他相关信息,在MVC5中,它似乎表现为该标志为真,即使对于未在WebForms中看不到的未捕获异常,它也是假的。作为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;
}

答案 1 :(得分:2)

如果您需要使用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"用于一个(或几个)代码。