1

我使用类将数据写入http响应PushStreamContent。我需要检索适当的 HTTP 状态代码取决于onStreamAvailable委托执行的结果。这是一个示例代码:

[HttpGet]
public HttpResponseMessage Get(int id)
{
    try
    {
        HttpResponseMessage response = this.Request.CreateResponse();
        response.Content = new PushStreamContent((Stream outputStream, HttpContent content, TransportContext context) =>
        {
            try
            {
                throw new Exception("Just an exception");

                response.StatusCode = HttpStatusCode.OK;
            }
            catch (Exception ex)
            {
                using (StreamWriter sw = new StreamWriter(outputStream))
                {
                    sw.WriteLine(ex.Message);
                    sw.Flush();
                }

                response.StatusCode = HttpStatusCode.InternalServerError;
            }
        });

        return response;
    }
    catch (Exception ex)
    {
        return this.Request.CreateErrorResponse(HttpStatusCode.InternalServerError, ex);
    }
}

上面的示例总是检索状态代码 200(Ok)。我该如何解决?

4

1 回答 1

1

您无法在 PushStreamContent 操作中修复它。当您设置状态码时,您已经开始发送响应,因此已经发送了 200。这是 PushStreamContent 的一个缺点。

于 2017-12-21T16:14:26.070 回答