Web响应状态代码

我有这个简单的函数来获取HTML页面并将其作为字符串返回; 虽然有时我得到404.如果请求成功,我怎么才能返回HTML字符串,当它是404或任何其他错误状态代码时返回BadRequest之类的东西?

 public static string GetPageHTML(string link) { using (WebClient client= new WebClient()) { return client.DownloadString(link); } } 

您可以捕获WebException:

 public static string GetPageHTML(string link) { try { using (WebClient client = new WebClient()) { return client.DownloadString(link); } } catch (WebException ex) { var statusCode = ((HttpWebResponse)ex.Response).StatusCode; return "An error occurred, status code: " + statusCode; } } 

当然,在调用代码中捕获此exception更为合适,甚至不会尝试解析html而不是将try / catch放在函数本身中。