Http response.ContentLength总是返回-1 c#

时间:2017-03-14 05:40:13

标签: c# asp.net httprequest

我正在尝试测量ASP.Net应用程序中的内容长度,如showen:

Stopwatch sto = new Stopwatch();
                HttpWebRequest request = (HttpWebRequest)WebRequest.Create("https://www.google.com");

                sto.Start();
                HttpWebResponse response = (HttpWebResponse)request.GetResponse();
                response.Close();
                sto.Stop();

                int statusCode = (int)response.StatusCode; //save status code as int
                if (response!= null) //reply.Status == System.Net.NetworkInformation.IPStatus.Success)
                {

                    pinglbl.Text += "Latncy: " + sto.Elapsed.TotalSeconds + " s";
                    pinglbl.Text += "\r Status Code: " + statusCode;
                    pinglbl.Text += "\r Content Lenghth: " + response.ContentLength +"MB";

                }
                else
                    pinglbl.Text = "fail ping";

我总是得到这个输出:
 结果历史:0.6525514 s状态代码:200内容长度: -1MB

是否存在持续获得-1作为内容长度的问题?

2 个答案:

答案 0 :(得分:3)

MSDN中所述:

  

ContentLength属性包含随响应返回的Content-Length标头的值。如果未在响应中设置Content-Length标头, ContentLength将设置为值-1。

答案 1 :(得分:0)

问题是所有测试的链接都没有包含任何内容长度,我尝试过来自SourceForge的this链接并且工作正常。