如何使用HttpListener / HttpListenerResponse返回带有正文的错误页面

Mvd*_*vdV 3 http http-status-codes httplistener httplistenerrequest c#-4.0

我正在使用.NET(C#)中的HttpListener创建REST API。除了一个小问题,这一切都很好。

我试图返回状态码不是OK(200)的响应,例如ResourceNotFound(404)。

当我将HttpListenerResponse的StatusCode设置为200以外的其他值,并创建一个响应主体(使用HttpListenerResponse.OutputStream)时,似乎将状态码重置为200。我无法使用StatusCode 404和消息正文。但是,根据HTTP规范,这应该是可能的。我正在用Fiddler检查请求和响应,但无法获得所需的内容。

56k*_*6ka 5

我遇到了同样的问题,并找到了问题的根源:

如果您在(或任何其他属性)设置OutputStream 之前写入正文,则将应用修改之前StatusCode发送响应!

因此,您必须按以下顺序进行:

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);
}
Run Code Online (Sandbox Code Playgroud)