【问题标题】:How to return error pages with body using HttpListener/HttpListenerResponse如何使用 HttpListener/HttpListenerResponse 返回带有正文的错误页面
【发布时间】:2012-09-28 02:52:57
【问题描述】:

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

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

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

【问题讨论】:

  • 我在创建资源时遇到了同样的问题,即返回“201”。当返回的状态码是“200”(OK)以外的内容时,内容正文似乎是空的。

标签: http c#-4.0 http-status-codes httplistener httplistenerrequest


【解决方案1】:

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

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

所以,你必须按照这个顺序进行:

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);
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-04-06
    • 1970-01-01
    • 2021-05-22
    • 1970-01-01
    • 2020-05-23
    • 2019-03-24
    • 1970-01-01
    相关资源
    最近更新 更多