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

时间:2017-03-10 11:44:54

标签: c# httpresponse http-response-codes pushstreamcontent

我使用PushStreamContent类将数据写入http响应。我需要检索适当的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(确定)。我怎么解决它?

1 个答案:

答案 0 :(得分:1)

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