简体   繁体   English

来自HttpWebResponse的Stream的奇怪行为

[英]Strange behavior of Stream from HttpWebResponse

I experienced some strange issue while reading stream from HttpWebResponse. 从HttpWebResponse读取流时遇到了一些奇怪的问题。 In case of successful response (200 status code) I get exception when access to Length property of stream. 在成功响应的情况下(200状态代码),当访问流的Length属性时出现异常。 But in case of WebException when server returns some error (eg BadRequest) everything is perfect, Length works ok. 但是在WebException的情况下,当服务器返回一些错误(例如BadRequest)时,一切都完美无缺,Length可以正常工作。 I can get ContentLength directly from HttpWebResponse but want to know the reason of such behavior. 我可以直接从HttpWebResponse获取ContentLength,但想知道这种行为的原因。 Here is debug screenshot of both cases 这是两种情况的调试屏幕截图

        try
        {
            var request = (HttpWebRequest) WebRequest.Create(uriString);
            request.Method = HttpMethod.Get.Method;
            request.ContentType = "application/json";
            response = (HttpWebResponse) request.GetResponse();
            statusCode = response.StatusCode;
            responseString = DecodeResponse(response);
        }
        catch (WebException ex)
        {
            response = (HttpWebResponse) ex.Response;
            responseString = DecodeResponse(response);
            statusCode = response.StatusCode;
        }

        private static string DecodeResponse(HttpWebResponse response)
        {
            byte[] data;
            using (Stream stream = response.GetResponseStream())
            {
                data = new byte[stream.Length];
                stream.Read(data, 0, data.Length);
            }
            return Encoding.UTF8.GetString(data);
        }

The stream (ConnectStream) which is being created internally as part of the response does not support the Length property. 在内部作为响应的一部分创建的流(ConnectStream)不支持Length属性。 Different streams support different properties depending on their implementation. 不同的流根据其实现支持不同的属性。

You could use a different way to read from the stream as in this post: 您可以使用其他方式从流中读取内容,如下所示:

C# How do i convert System.Net.ConnectStream to a byte[] (array) C#如何将System.Net.ConnectStream转换为byte [](数组)

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

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