如何成功使用existingResponse ="Auto"?

Bra*_*ney 23 c# iis asp.net-mvc

所以我从我的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");
}
Run Code Online (Sandbox Code Playgroud)

Mic*_*ael 39

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

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

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

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

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

Response.TrySkipIisCustomErrors = true;
Run Code Online (Sandbox Code Playgroud)

这就是你所看到的.


其他相关的信息,在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;
}
Run Code Online (Sandbox Code Playgroud)


Łuk*_*zyk 7

如果您需要具有 4xx http 状态的自定义响应,并且仍想使用自定义错误页面,您应该这样做:

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

奇怪的是,IIS 团队没有existingResponse为特定的状态代码实现属性,因此不可能existingResponse="PassThrough"仅用于一个(或几个)代码。