附加信息:远程服务器返回错误:(404)Not Found。 MVC

时间:2017-02-22 17:32:44

标签: c# asp.net-mvc webclient

我试图获取https://www.americasarmy.com/soldier/1309069

的源代码

使用以下代码:

using (WebClient client = new WebClient())
{

    ViewBag.htmlCode = client.DownloadString("https://www.americasarmy.com/soldier/1309069");
}

1 个答案:

答案 0 :(得分:1)

当它返回404时,源字符串将位于WebException.Response:

try
{
    client.DownloadString("https://www.americasarmy.com/soldier/1309069");
}
catch (WebException webex)
{
    using (var streamReader = new StreamReader(webex.Response.GetResponseStream()))
    {
        var htmlCode = streamReader.ReadToEnd(); 
    }
}