HttpResponse - 如何设置状态码取决于 PushStreamContent 执行结果

HttpResponse - how to set status code depends on PushStreamContent execution result

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

[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)。我该如何解决?

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