繁体   English   中英

在流式响应中途设置http状态

[英]Setting the http status midway through a streamed response

我正在流式传输HTTP响应,并且在执行过程中出错,这在下面进行了模拟。 最终用户将其视为200响应,因为我知道状态是在响应标头中发送的。 到我的错误发生时,我已经抓住了它,并将状态重置为500,为时已晚。 流原始头后,如何将“真实”状态设置为500?

var httpResponse = HttpContext.Current.Response;
httpResponse.BufferOutput = false;
httpResponse.ContentType = "application/xml";
try
{
    httpResponse.Write("<?xml version=\"1.0\" encoding=\"utf-8\"?>" + Environment.NewLine);
    httpResponse.Write($"<{Constants.XmlHeaderTag}>");
    var theline = 0;
    while (some condition)
    {
        if (theline++ == 3) throw new Exception("Got an error");
        var innerXml = "some xml";
        httpResponse.BinaryWrite(Encoding.UTF8.GetBytes(innerXml));
    }
    httpResponse.Write($"</{Constants.XmlHeaderTag}>");
    httpResponse.OutputStream.Flush();
    httpResponse.End();
}
catch (Exception ex)
{
    httpResponse.Status = 500;
    logError(ex);
}

你不能。 http标头位于有效负载中的数据之前 标头发送之后:它们就被发送了。 此后您将无法设置标头,即使可以,也没有客户端会理解您的意思,因为在有效负载期间无法接收标头。 您所能做的就是扼杀回应; 客户端会知道他们还没有得到所有信息(假设您发送了一个Content-length标头),并且xml格式错误(未正确终止),因此他们会发现它早晚会损坏。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM