首页 > 解决方案 > WebClient 为有效的 URI 返回 HTTP 404

问题描述

我想获取带有源代码的页面的html:

try {
  var webContent = "";
  using (WebClient client = new WebClient ()) {
    client.Headers.Add (HttpRequestHeader.UserAgent, "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/69.0.3497.100 Safari/537.36");

    webContent = client.DownloadString (@"http://localhost:8080/account/login");
  }
} catch (WebException ex) {
  var responseText = string.Empty;
  var responseStream = ex.Response?.GetResponseStream ();

  if (responseStream != null) {
    using (var reader = new System.IO.StreamReader (responseStream)) {
      responseText = reader.ReadToEnd ();
    }
  }
}

我可以获得http://localhost:8080/的内容。但是使用http://localhost:8080/account/login,它会返回“Cannot GET /account/login”。我可以通过浏览器浏览到这个网址。

如何使用 WebClient获取http://localhost:8080/account/login的 html?

谢谢,

标签: c#webclient

解决方案


打开 Chrome 和开发者工具(按 F12)。打开网络选项卡。

导航到http://localhost:8080/account/login

您可能会看到重定向或 2(检查 302)。下面的页面可以帮助您找出正在重定向的页面。

您也可以使用 powershell 进行测试

wget http://localhost:8080/account/login

推荐阅读