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放在函数本身中。
- 隐式运算符,generics不适用于接口
- 使用Jabber.net(C#/ Mono)和SASL连接到Facebook聊天
- 在更新面板中突出显示gridview行而不回发
- C#:异步NamedPipeServerStream管道正在关闭exception
- ViewStartPage只能与从WebViewPage或其他ViewStartPage派生的页面一起使用
- 无法将类型’System.Linq.IQueryable ‘隐式转换为’int?’
- 在C#中将Exe文件作为嵌入式资源运行
- 如何在使用XmlSerializer保留内容的同时更改根元素名称?
- 如何在ASP.NET Core 1.0中配置身份validation