WebRequest.GetResponse()返回空流结果,但Fiddler显示响应中的内容

时间:2016-01-19 10:36:41

标签: c# web

我尝试使用代码保存从远程服务器收到的二进制数据:

public static WebObjectResponse<byte[]> RequestBinary(string uri)
{
    var streamData = GetResponseStream(uri);
    if (streamData.StatusCode != 200)
    {
        return new WebObjectResponse<byte[]> {Result = new WebRequestResult(streamData.StatusCode)};
    }

    if (streamData.ContentLength == -1)
    {
        return new WebObjectResponse<byte[]> {Result = new WebRequestResult(204)}; // 204 = No Content
    }

    using (streamData.Stream)
    {
        var responseBuffer = new byte[streamData.ContentLength];
        streamData.Stream.Read(responseBuffer, 0, responseBuffer.Length);
        return new WebObjectResponse<byte[]>
        {
            Data = responseBuffer,
            Result = WebRequestResult.CreateSuccessfull()
        };
    }
}

private static WebStreamResponse GetResponseStream(string uri)
{
    try
    {
        var response = CreateRequest(uri).GetResponse();
        return new WebStreamResponse
        {
            StatusCode = 200,
            Stream = response.GetResponseStream(),
            ContentLength = response.ContentLength
        };
    }
    catch (WebException e)
    {
        return new WebStreamResponse {StatusCode = (int) ((HttpWebResponse) e.Response).StatusCode};
    }
    catch (Exception e)
    {
        throw;
    }
}

response.ContentLength的值为-1,但Fiddler向我展示了另一张图片:

Fiddler session result

这就是为什么我必须添加一个双重检查(response.ContentLength!= -1)以防止异常抛出。

我如何更改C#代码以接收有效的响应流?

0 个答案:

没有答案