C# 网页响应状态码
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/15289440/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Web Response status code
提问by user1590636
I have this simple function to get HTML pages and return it as a string; though sometimes I get a 404. How can I only return the HTML string only if the request was successful, and return something like BadRequest
when it's a 404 or any other error status code?
我有一个简单的函数来获取 HTML 页面并将其作为字符串返回;虽然有时我会得到 404。我怎么能只在请求成功时才返回 HTML 字符串,并BadRequest
在它是 404 或任何其他错误状态代码时返回类似的东西?
public static string GetPageHTML(string link)
{
using (WebClient client= new WebClient())
{
return client.DownloadString(link);
}
}
采纳答案by Darin Dimitrov
You could catch the WebException:
您可以捕获 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;
}
}
Of course it would be more appropriate to catch this exception in the calling code and not even attempt to parse the html instead of putting the try/catch in the function itself.
当然,在调用代码中捕获此异常甚至不尝试解析 html 而不是将 try/catch 放在函数本身中会更合适。