【问题标题】:Http response.ContentLength always return -1 c#Http response.ContentLength 总是返回 -1 c#
【发布时间】:2017-03-14 05:40:13
【问题描述】:

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

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";

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

内容长度一直为 -1 有什么问题吗?

【问题讨论】:

  • 我猜响应实际上并不包含Content-Length 标头。
  • @CoryNelson 是的 -1 表示但我尝试了许多其他网址但输出仍然相同。

标签: c# asp.net httprequest


【解决方案1】:

MSDN中所述:

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

【讨论】:

  • 我已经阅读了你提到的这篇文章,但是我看到的所有教程都写了相同的代码 - 就像我所拥有的一样 - 但它们得到的结果与 -1 不同
  • 以此为例[链接] (msdn.microsoft.com/en-us/library/…)
  • 只需在打开开发工具的 chrome 中打开您的 URL,然后查找 Content-Length 标头作为响应 - 您不会看到它。尝试另一个提供此标头的网站。
  • 好的,我会试试的。
【解决方案2】:

问题是作为输入测试的所有链接都不包含任何内容长度,我尝试了 SourceForge 的 this 链接,它工作正常。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-04-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-11-21
    • 2019-10-10
    • 2014-04-13
    • 2017-03-20
    相关资源
    最近更新 更多