如何在 ASP.Net 中发送状态代码 500 并仍然写入响应? [英] How to send a Status Code 500 in ASP.Net and still write to the response?

查看:14
本文介绍了如何在 ASP.Net 中发送状态代码 500 并仍然写入响应?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have an ASP.Net single-file web service (a .ashx file containing an IHttpHandler implementation) which needs to be able to return errors as responses with 500 Internal Server Error status codes. This is a relatively straightforward thing to do in PHP:

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

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

The ASP.Net (C#) equivalent should be:

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

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

Of course, this doesn't work as expected; instead, IIS intercepts the 500 status code, trashes whatever I've written to the Response object, and sends either debug info or a custom error page, depending on how the app is configured.

我的问题 - 如何抑制这种 IIS 行为并直接从我的 IHttpHandler 实现发送错误信息?

My question - how can I suppress this IIS behaviour and send error information directly from my IHttpHandler implementation?

这个应用程序是从 PHP 移植过来的;客户端已经写好了,所以我基本上坚持这个规范.可悲的是,发送带有 200 状态代码的错误不适合这种模式.

This app is a port from PHP; the client-side is already written, so I'm essentially stuck with this spec. Sending errors with a 200 status code sadly doesn't fit the mould.

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

Ideally, I need to control the behaviour programmatically, because this is part of an SDK we want to distribute without any "edit this file" and "change this IIS setting" supplementary instructions.

谢谢!

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

Edit: Sorted. Context.Response.TrySkipIisCustomErrors = true was the ticket. Wow.

推荐答案

Context.Response.TrySkipIisCustomErrors = true

这篇关于如何在 ASP.Net 中发送状态代码 500 并仍然写入响应?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆