如何在ASP.Net中发送状态代码500并仍然写入响应?

Nei*_*son 64 c# asp.net rest ihttphandler

我有一个ASP.Net单文件Web服务(.ashx包含IHttpHandler实现的文件),它需要能够将错误返回为具有500个内部服务器错误状态代码的响应.这在PHP中是相对简单的事情:

header("HTTP/1.1 500 Internal Server Error");
header("Content-Type: text/plain");
echo "Unable to connect to database on $dbHost";
Run Code Online (Sandbox Code Playgroud)

ASP.Net(C#)等效应该是:

Context.Response.StatusCode = (int)HttpStatusCode.InternalServerError;
Context.Response.ContentType = "text/plain";
Context.Response.Write("Unable to connect to database on " + dbHost);
Run Code Online (Sandbox Code Playgroud)

当然,这不能按预期工作; 相反,IIS拦截500状态代码,删除我写入Response对象的任何内容,并发送调试信息或自定义错误页面,具体取决于应用程序的配置方式.

我的问题 - 我怎样才能抑制这种IIS行为并直接从我的IHttpHandler实现中发送错误信息?

这个应用程序是PHP的一个端口; 客户端已经写好了,所以我基本上坚持这个规范.错误地发送200状态代码的错误不适合模具.

理想情况下,我需要以编程方式控制行为,因为这是我们要分发的SDK的一部分,而没有任何" 编辑此文件 "和" 更改此IIS设置 "补充说明.

谢谢!

编辑:已排序.Context.Response.TrySkipIisCustomErrors = true是票.哇.

Nei*_*son 110

Context.Response.TrySkipIisCustomErrors = true

  • IIS7中支持 - http://msdn.microsoft.com/en-us/library/system.web.httpresponse.tryskipiiscustomerrors%28v=VS.90%29.aspx (6认同)

Pai*_*ook 10

我以前使用过以下内容,并且能够使用Page_Load方法中显示的代码在自定义消息中抛出503错误.我在负载均衡器后面使用此页面作为负载均衡器的ping页面,以了解服务器是否在服务中.

希望这可以帮助.

        protected void Page_Load(object sender, System.EventArgs e)
    {
        if (Common.CheckDatabaseConnection())
        {
            this.LiteralMachineName.Text = Environment.MachineName; 
        }
        else
        {
            Response.ClearHeaders();
            Response.ClearContent(); 
            Response.Status = "503 ServiceUnavailable";
            Response.StatusCode = 503;
            Response.StatusDescription= "An error has occurred";
            Response.Flush();
            throw new HttpException(503,string.Format("An internal error occurred in the Application on {0}",Environment.MachineName));  
        }
    }
Run Code Online (Sandbox Code Playgroud)