[英]How to return error pages with body using HttpListener/HttpListenerResponse
我正在使用.NET(C#)中的HttpListener创建REST API。 这一切都很好,除了一个小问题。
我正在尝试使用状态代码而不是OK(200)返回响应,例如ResourceNotFound(404)。
当我将HttpListenerResponse的StatusCode设置为200以外的其他东西,并创建一个响应体(使用HttpListenerResponse.OutputStream)时,它似乎将状态代码重置为200.我无法使用StatusCode 404发送响应和一个消息体。 但是,根据HTTP规范,这应该是可能的。 我正在和Fiddler一起检查请求和回复,但我无法得到我正在寻找的东西。
我遇到了同样的问题并找到了问题的根源:
如果在设置StatusCode
(或任何其他属性) 之前在OutputStream
编写正文,则会在应用修改之前发送响应!
所以,你必须按以下顺序进行:
public void Send(HttpListenerContext context, byte[] body)
{
// First, set a random status code and other stuffs
context.Response.StatusCode = (int)HttpStatusCode.Unauthorized;
context.Response.ContentType = "text/plain";
// Write to the stream IN LAST (will send request)
context.Response.OutputStream.Write(body, 0, body.Length);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.